Jem Jem - 5 months ago 17
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

Example:

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


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

.css-form input.ng-invalid.ng-dirty {

background-color: #FA787E;
}

Answer

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).

EDIT

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
    if(angular.isDefined(e))
        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>
</ng-messages>

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.

Comments