在这里使用angular js:
我有一个文本框,我想在其中应用某些正则表达式并阻止用户使用某些字符。以下是我想要的:
-
防止用户以下划线开始和结束。
-
-
允许使用字符和数字,并且可以以任意一个开头或结尾
-
字符/数字之间只允许使用下划线,并且在
开始或结束。
-
文本框:
<input type="text" name="uname" ng-model="uname" required class="form-
control input-medium" placeholder="Enter name..." maxlength="20" restrict-
field="alpha-numeric" ng-trim="false" />
.directive("restrictField", function() {
return {
require: "ngModel",
restrict: "A",
link: function(scope, element, attrs, ctrl) {
var regReplace,
preset = {
"alphanumeric-spl": "\\w_./s/g",
"alphanumeric-underscore": "\\w_",
"numeric": "0-9",
"alpha-numeric": "\\w"
},
filter = preset[attrs.restrictField] || attrs.restrictField;
ctrl.$parsers.push(function(inputValue) {
regReplace = new RegExp('[^' + filter + ']', 'ig');
if (inputValue == undefined) return "";
cleanInputValue = inputValue.replace(regReplace, "");
if (cleanInputValue != inputValue) {
ctrl.$setViewValue(cleanInputValue);
ctrl.$render();
}
return cleanInputValue;
});
}
};
});
虽然上述方法适用于我在指令中使用的简单模式,但不适用于我上面描述的模式。从我的另一篇文章中,我得到了用于正则表达式负前瞻的模式,如下所示:
^(?!_)(?!.*_$)[a-zA-Z0-9_]+$
但是,如果我试图将其包含在指令中,这是行不通的。
以下是我创建的示例代码笔:
https://codepen.io/anon/pen/LJBbQd