Force ng-dirty in angularjs form validation

All we need is an easy explanation of the problem, so here it is.

Doing form validation with angularjs I want to mark all required fields as erroneous when the user click submit.

I am using input.ng-dirty.ng-invalid to style the controls with error. So what I want is to set ng-dirty on required controls (or all controls.. it will be the same for me) when the user submits the form.

Validation is working. I understand why, what I am trying could be wrong, but I found no other way to do the same effect, except something that I think is too complicated to be right.

What I tried was:

<div ng-app>
    <form novalidate>
        <input name="formvalue" type="text" ng-model="formvalue" required />
        <input type="submit" />
    </form>
</div>

http://jsfiddle.net/yq4NG/

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Let’s start by adding angular to your jsfiddle by wrapping it in

<div ng-app>...</div>

http://jsfiddle.net/yq4NG/1/

By default the required field will be validated on input (dirty). If you want to have them validated on submit before any input (pristine), then you can run a function on your submit button that will check for pristine fields and dirty them.

That is what i have done in the example: http://jsfiddle.net/yq4NG/6/

You could probably build a reusable solution using custom formatters and validators but this is a simple on off solution.

EDIT:

Simpler again using just classes: http://jsfiddle.net/yq4NG/8/

EDIT [as suggested by @XMLilley in the comments]:

Because angular doesn’t provide a $setDirty() method that’s equivalent to $setPristine() we’re triggering the $dirty state by simply updating the $viewValue with the contents of the $modelValue. It changes nothing, but simulates a user having manually entered each $pristine field and messed around with the value without changing anything.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply