Jem Jem - 1 year ago 86
AngularJS Question

Angular.js: Set form fields "dirty" upon submission

How can I make a form input to become dirty as the form is submitted?

This is needed so that the input fields with an $error can be


name: <input type="text"
ng-model-options="{ updateOn: 'blur' }"
required /><br/>

As the form is submitted, I want this field - if left blank - to be rendered using the "invalid & dirty" style:

.css-form {

background-color: #FA787E;

Answer Source

Disable the submission button until form is dirty and the form items are valid.

<button type="submit" class="btn btn-primary" ng-disabled="myFrmName.$invalid || !myFrmName.$dirty">Submit Form</button>

Using ng-disabled will disable the form submission button while the form is $invalid or the form has yet to be touched (not $dirty).


I usually do something like this to display an error next to the required field:

<input type="text" name="myField" required ng-class="{true : 'has-error'}[hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)]>
<span ng-if="hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)">Required!</span>

Then in your controller:

$scope.hasError = function(e,d){ // e = $error, d = $dirty
        return e && d;

    return false;
} // end hasError

Example with ngMessages (Angular 1.3)

<input type="text" name="myField ng-model="fields.myField" ng-class="{true : 'has-error'}[hasError(myFrmName.myField.$error.required,myFrmName.myField.$dirty)] required>
<ng-messages for="myFrmName.myField.$error" ng-if="myFrmName.myField.$dirty">
    <ng-message when="required" class="text-danger">The field is required!</ng-message>

The great thing about ngMessages is that all you need to do is add more <ng-message> tags for each type of validation for the field and just change the when attribute approrpriately.

<ng-message when="minlength">Your entry is too short.</ng-message>

Angular will display the correct message based upon whether or not the when is in the $error object for the field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download