0
我搜索,我知道'指令的方式'做自定義驗證,但它看起來像對我來說矯枉過正,我希望有一個更簡單的方法,所以我嘗試了這樣的東西。更好的自定義驗證角形
它的作品,但真的不知道它是正確的方式(或角度的方式)。
.controller('vali', ['$scope', function vali($scope) {
var th = this
th.formData = {}
// watch password repeat
$scope.$watch(function() {
return th.password1
}, function(newPass) {
if(!customValidate(newPass)) th.form.pass2.$setValidity('custom', false)
else th.form.pass2.$setValidity('custom', true)
})
//custom validate: password repeat must equal to password
function customValidate(v) {
if(v === th.formData.password) return true
else return false
}
this.submit = function(form) {
if(!th.form.$invalid) th.postToServer(th.formData)
}
this.postToServer = function(data) {
//do post to server
console.log(data)
}
}])
HTML:
<div ng-controller='vali as v'>
<form name='v.form' ng-submit='v.submit'>
<input type='password' name='pass1' ng-model='v.formData.password' minlength='6' />
<input type='password' name='pass2' ng-model='v.password1' />
<div ng-messages='v.form.pass2.$error' ng-if='v.form.pass2.$dirty'>
<div ng-message='required'>required</div>
<div ng-message='custom'> not equal</div>
</div>
<button type='submit'>submit</button>
</form>
</div>
是的,這是更好.. – 2015-04-02 05:57:06