<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<form id="registerform" class="form-horizontal" role="form" novalidate="novalidate" name="registrationForm">
<div style="margin-bottom: 25px" ng-class="{ 'has-error' : registrationForm.password.$invalid && !registrationForm.password.$pristine }">
<input id="register-password1" type="password" class="form-control" name="password" placeholder="Password" ng-model="password" ng-maxlength="25" ng-minlength="6" ng-required="true" onkeypress="return (event.which != 32)">
<p ng-show="registrationForm.password.$error.required && !registrationForm.password.$pristine" class="help-block errosClass">Please enter password</p>
<p ng-show="registrationForm.password.$dirty && registrationForm.password.$error.maxlength" class="help-block errosClass">Password cannot be more than 25 characters</p>
<p ng-show="registrationForm.password.$dirty && registrationForm.password.$error.minlength" class="help-block errosClass">Password cannot be less than 6 characters</p>
</div>
<div style="margin-bottom: 10px" ng-class="{ 'has-error' : registrationForm.cpassword.$invalid && !registrationForm.cpassword.$pristine }">
<input id="register-confirm-password" type="password" class="form-control" name="cpassword" placeholder="Confirm Password" ng-model="cpassword" ng-pattern="password" required="required" onkeypress="return (event.which != 32)">
<p ng-show="registrationForm.cpassword.$error.required && !registrationForm.cpassword.$pristine" class="help-block errosClass">Please enter confirm password</p>
<p ng-show="registrationForm.cpassword.$error.pattern" class="help-block errosClass">Your password and confirm password not match.</p>
</div>
</form>
</div>
</body>
</html>
答案 0 :(得分:0)
在ng-pattern
中,您需要传递正则表达式。符号$
是regexp中字符串的结尾。
对于真正的验证,您需要创建像
这样的指令export class PasswordMatchValidator {
constructor() {
this.require = 'ngModel';
this.restrict = 'A';
}
link($scope, $element, $attrs, ngModel) {
ngModel.$validators.passwordMatch = modelValue =>
$attrs.passwordMatch == modelValue;
$attrs.$observe( 'passwordMatch', () => ngModel.$validate() );
}
}
并在
模板中使用它<p ng-show="registrationForm.cpassword.$error.passwordMatch" class="help-block errosClass">Your password and confirm password not match.</p>
答案 1 :(得分:0)
此:
ng-pattern="password"
...不是确保password
和cpassword
相同的可靠方法。除了没有特殊字符的简单字母数字文本的情况,不是您想要密码的限制,您不能期望字符串自我验证自身作为正则表达式。
您需要直接比较password
与cpassword
进行验证。
答案 2 :(得分:0)
正如所写,$被视为正则表达式的结束。
所以有助于摆脱它。
将ng-pattern="password"
替换为ng-pattern="password.replace('$', '\\$')"
(您通过\ $转义$,双\是转义\本身;)