0

I searched, I know 'the directive way' to do custom validation, but it looks like a overkill to me, I hope there is a simpler way, so I tried somwthing like this.

it works, but really not sure it is the right way(or angular way).

.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
  • yeah, this is better .. Commented Apr 2, 2015 at 5:57

1 Answer 1

2

You don't need to create your own directive for this. There is already a built-in directive for the password validation. You can use that like this :

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

The input will be valid when the expression in ui-validate is true, so you can have any validation you want by changing the expression.

Sign up to request clarification or add additional context in comments.

1 Comment

ui-validate seems just what i need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.