在此处使用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_]+$
但是,如果我尝试将其包含在指令中,则此方法将无效。
这是我创建的示例Codepen:https://codepen.io/anon/pen/LJBbQd
如何应用上述正则表达式。如果不是这样,是否有解决方法或任何其他方法来使用此正则表达式限制我的文本框。
谢谢
答案 0 :(得分:0)
我建议在末尾允许_
,并使用带有正则表达式的HTML5模式属性,该属性要求最后一个字符为除_
和pattern=".*[^_]"
之外的任何字符。如果需要允许使用空字符串,请使用pattern="(?:.*[^_])?"
。
var app = angular
.module("myApp", ["ui.bootstrap"])
.directive("restrictField", function() {
return {
require: "ngModel",
restrict: "A",
link: function(scope, element, attrs, ctrl) {
var regReplace,
preset = {
'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
'alphanumeric-underscore': '^_+|_+(?=_)|\\W+', // Removes all _ at start and all _ before a _ and all but alnum and _
'numeric': '[^0-9]+', // Removes all but digits
'alpha-numeric': '[\\W_]+' // Removes all but alnum
},
filter = preset[attrs.restrictField] || attrs.restrictField;
ctrl.$parsers.push(function(inputValue) {
console.log(filter);
regReplace = RegExp(filter, 'ig');
if (inputValue == undefined) return "";
cleanInputValue = inputValue.replace(regReplace, "");
if (cleanInputValue != inputValue) {
ctrl.$setViewValue(cleanInputValue);
ctrl.$render();
}
return cleanInputValue;
});
}
};
});
// Define the `appController` controller on the `ReportsMockUpsApp` module
app.controller("ctrl", function($scope) {});
body {
padding: 10px
}
input:valid {
color: black;
border: 5px solid #dadadada;
border-radius: 7px;
}
input:invalid {
color: navy;
outline: .glowing-border:focus;
border-color: #ff1050;
box-shadow: 0 0 10px #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
<script src="https://code.angularjs.org/1.3.4/angular.min.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="ctrl">
<label>Wow</label>
<input type="text" pattern=".*[^_]" name="uname" ng-model="uname" required class="form-control input-medium" placeholder="Enter name..." maxlength="20" restrict-field="alphanumeric-underscore" ng-trim="false" />
</div>
</div>