我試圖創建自己的密碼確認驗證,並將錯誤放在$ error上。這是我的代碼:輸入即使在錯誤爲空時也是無效的
HTML:
<input ng-model="user.password2" type="password" name="password2" required
ng-keyup="confirmPassword(user.password, user.password2)">
<div ng-messages="register.password2.$error" ng-if="register.password2.$dirty">
<div ng-message="required">Password is required</div>
<div ng-message="passwordsDontMatch">Passwords don't match</div>
</div>
JS:
$scope.confirmPassword = function (pass1, pass2) {
if (angular.isUndefined(pass1) || angular.isUndefined(pass2) || pass1.trim() != pass2.trim()) {
$scope.register.password2.$error["passwordsDontMatch"] = true;
} else {
delete $scope.register.password2.$error["passwordsDontMatch"];
}
console.log($scope.register.password2.$error);
};
它看起來像它的工作。當密碼相同時,消息不會顯示,並且$ error對象是空的。但輸入仍然無效:($scope.register.password2.$invalid == true
)
你可以看到我在這個plunkr中所說的:http://plnkr.co/edit/ETuVqsdSaEBWARvlt4RR?p=preview 嘗試2個相同的密碼。該消息將消失,但是當你從輸入模糊時,它仍然是紅色的,因爲它在內部是非法的
切換到$ setValidity()修復它,謝謝! –