更好的角形式自定义验证

时间:2015-04-02 05:55:39

标签: angularjs forms

我搜索过,我知道“进行自定义验证的'指令方式',但对我来说这看起来有点过分,我希望有一种更简单的方法,所以我尝试了这样的事情。

它有效,但真的不确定它是正确的方式(或有角度的方式)。

.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>

1 个答案:

答案 0 :(得分:2)

您不需要为此创建自己的指令。密码验证已有内置指令。 你可以这样使用:

<input name="password" required ng-model="password">
<input name="confirm_password"
   ui-validate=" '$value==password' "
   ui-validate-watch=" 'password' ">

当ui-validate中的表达式为true时,输入有效,因此您可以通过更改表达式进行任何所需的验证。

相关问题