我试图确保字段的最后一个字母必须在angularjs文本字段中以特定字母结尾。我创建了一个处理模式验证的函数,如下所示
$scope.validatePattern = function () {
var typeSelected = $scope.sports_type;
if (typeSelected == 'Sports') { //the user selected sports from the above model
$scope.pointPattern = "^[\s\w]+[^(ess|essence)]$";
}
}
我在以下字段中使用该模式。
<label>Sports Option</label>
<input ng-model="option" ng-minlength="3" formcontrol name="option" type="text" ng-pattern="{{pointPattern}}" required>
<p ng-show="frmValidation.option.$invalid" class="input-error-message">Option is required</p>
<p ng-show="frmValidation.option.$error.pattern">Not valid! Must end with ess or essence</p>
ng模式为何无法验证字母必须以ess或本质结尾
最佳答案
要匹配以ess
,essence
或sports
结尾的字符串,可以使用
$scope.pointPattern = /(?:ess(?:ence)?|sports)$/;
请注意,您必须使用
RegExp
变量类型。它等于$scope.pointPattern = new RegExp("(?:ess(?:ence)?|sports)$");
,并且如果您打算匹配输入字符串中的子字符串,则它是必需的。如果计划使用字符串模式,则需要确保它与整个输入字符串匹配:
$scope.pointPattern = "^.*(?:ess(?:ence)?|sports)$";
图案细节
^
-字符串开始.*
-除换行符以外的任何0+个字符(?:ess(?:ence)?|sports)
-一个non-capturing group匹配项ess(?:ence)?
-ess
后跟可选的ence
子字符串|
-或sports
-一个sports
子字符串$
-字符串结尾。