更好的自定义验证角形
问题描述:
我搜索,我知道'指令的方式'做自定义验证,但它看起来像对我来说矫枉过正,我希望有一个更简单的方法,所以我尝试了这样的东西。更好的自定义验证角形
它的作品,但真的不知道它是正确的方式(或角度的方式)。
.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>
答
你并不需要创建自己的这个指令。已经有一个内置的密码验证指令。 您可以使用这样的:
<input name="password" required ng-model="password">
<input name="confirm_password"
ui-validate=" '$value==password' "
ui-validate-watch=" 'password' ">
的投入将是有效的,当在UI的验证表达式为true,所以你可以通过改变表达任何你想要的验证。
+0
ui-validate似乎正是我需要的。 – 2015-04-03 00:09:24
是的,这是更好.. – 2015-04-02 05:57:06