javascript - Force ng-dirty in angularjs form validation -
doing form validation angularjs want mark required fields erroneous when user click submit.
i using input.ng-dirty.ng-invalid style controls error. want set ng-dirty on required controls (or controls.. same me) when user submits form.
validation working. understand why, trying wrong, found no other way same effect, except think complicated right.
what tried was:
<div ng-app> <form novalidate> <input name="formvalue" type="text" ng-model="formvalue" required /> <input type="submit" /> </form> </div>
let's start adding angular jsfiddle wrapping in
<div ng-app>...</div>
by default required field validated on input (dirty). if want have them validated on submit before input (pristine), can run function on submit button check pristine fields , dirty them.
that have done in example: http://jsfiddle.net/yq4ng/6/
you build reusable solution using custom formatters , validators simple on off solution.
edit:
simpler again using classes: http://jsfiddle.net/yq4ng/8/
edit [as suggested @xmlilley in comments]:
because angular doesn't provide $setdirty()
method that's equivalent $setpristine()
we're triggering $dirty
state updating $viewvalue contents of $modelvalue
. changes nothing, simulates user having manually entered each $pristine
field , messed around value without changing anything.
Comments
Post a Comment