AngularJS-阻止用户键入无效输入 [英] AngularJS - stop user from typing invalid input
问题描述
我有一个输入文本框,我想将输入限制为仅字母数字(0-9,a-z,A-Z)且最大长度为15.
I have a input text box and I would like to restrict the input to only alpha numerics (0-9, a-z, A-Z) and with max length of 15.
我正试图通过angularjs实现这一点.
I am trying to acheive this in angularjs.
<input type="text" id="trackNumber" maxlength="15" ng-pattern="/^[a-zA-Z0-9]*$/" placeholder="" class="form-control" ng-model="trackNumber"/>
将最大长度"设置为15时,用户不能在框中输入第16个字符.
With "maxlength" set to 15, user cannot type 16th character in the box.
类似地,当用户键入任何特殊字符或空格时,我想防止按键"事件.目前,ng-pattern似乎并没有阻止用户键入无效的输入.
Similarly, when user types any special characters or white spaces, I would like to prevent "keypress" event. Currently, ng-pattern doesn't seem to stop user from typing invalid input.
该怎么办?
非常感谢您的帮助.
推荐答案
@Shawn Bush是正确的,这不是ng-pattern的默认行为.
@Shawn Bush is correct this is not the default behaviour of ng-pattern.
但是,请参阅我的朋克我创建了一个名为"regExInput"的指令,该指令具有一个必需的属性"regEx",并根据正则表达式检查该条目是否无效,从而针对每次击键返回false进行检查.
However please see my plunk I have created a directive called "regExInput" which takes a required attribute "regEx" and checks this against each key stroke returning false if the entry is invalid according to the regular expression.
指令的代码:
app.directive("regExInput", function(){
"use strict";
return {
restrict: "A",
require: "?regEx",
scope: {},
replace: false,
link: function(scope, element, attrs, ctrl){
element.bind('keypress', function (event) {
var regex = new RegExp(attrs.regEx);
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
}
};
});
我希望这会有所帮助.不要犹豫,要求对代码进行任何改进:)
I hope this helps. Do not hesitate to ask for any refinements to the code :)
我还从此处
这篇关于AngularJS-阻止用户键入无效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!