[英]AngularJS comparing two input values doesn't work as expected
我正在嘗試使用AngularJS比較兩個密碼值。 我禁用了提交按鈕,直到所有字段均有效。 但是,它無法正常運行。 輸入電子郵件和第一個密碼后,“提交”按鈕即被啟用。 但是,如果我在第二個密碼字段中鍵入其他內容,則提交按鈕將再次被禁用。 即使在第二個密碼字段中未輸入任何內容,我該如何進行驗證?
這是我的表格
<form ng-submit="submit()" name="register" class="form-signin" novalidate>
<h1 class="form-signin-heading text-muted">
Register
</h1>
<input name="email" ng-model="email" type="email" class="form-control" placeholder="Email address" required>
<p class="help-block" ng-show="register.email.$dirty && register.email.$invalid">Please enter a valid email</p>
<input name="password" ng-model="password" type="password"class="form-control" placeholder="Password" required>
<input name="password_confirm" ng-model="password_confirm" type="password" class="form-control" placeholder="Confirm Password" validate-equals='password'>
<p class="help-block" ng-show="register.password_confirm.$dirty && register.password_confirm.$invalid">The passwords do not match</p>
<button ng-disabled="register.$invalid" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
這是Javascript文件(validateEquals.js)
'use strict';
angular.module('jwtApp').directive('validateEquals', function () {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
function validateEqual(value) {
var valid = (value === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity('equal', valid);
return valid ? value : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
});
如果我可以提出建議,請執行以下操作:
<button ng-disabled="register.$invalid || password != password_confirm" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
並且不要在指令中使用validateEqual
實現。 這是一個小提琴: http : //jsfiddle.net/jochenvanwylick/U3pVM/13972/及其代碼和修復程序。 我不會將其變成指令,也不會嘗試加入元素的$parsers
和$formatters
。
嘗試這個
.directive('validateEquals', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.validateEquals;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
var v = elem.val()===$(firstPassword).val();
ctrl.$setValidity('inputmatch', v);
});
});
}
}
在html上,您可以像這樣檢查
<input type="password" id="input1" name="input1" ng-model="input1" ng-required/>
<input type="password" id="input2" name="input2" ng-model="input2" ng-required validate-equals="input1"/>
希望會幫助這個解決方案:)
編輯
可以顯示這樣的錯誤消息
<div ng-show="myForm.$error">
<span ng-show="myForm.input2.$error.inputmatch">
Passwords don't match.
</span>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.