mercredi 1 avril 2015

better custom validation for angular form

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>

Aucun commentaire:

Enregistrer un commentaire