Do not trigger form.$invalid on first load

Keeps Keeps picture Keeps Keeps · Aug 5, 2015 · Viewed 7.9k times · Source

Having such form

    <div ng-controller="FormController as f_ctrl">
    <form ng-submit="f_ctrl.submit()" name="myForm">
    <input type="text" ng-model="f_ctrl.user.username"
            required
            ng-minlength="4"/>
    <input type="text" ng-model="f_ctrl.user.password"/>
    <input type="submit" value="Submit" ng-disabled="myForm.$invalid">
    </form>
</div>

and such controller

    .controller('FormController', [function() {
    var self = this;

    self.submit = function() {
        console.log('User submitted form with ' + self.user.username)
    }
}]);

I have a problem: when page first loads it immediately shows red border on username field, even before I start typing anything. I need to highlight invalid fields only after first submission. Can this be done using form.$invalid ?

Answer

Paresh Gami picture Paresh Gami · Aug 5, 2015

You have to use $pristine for that. It is true when form controller is not changed. so when you change textbox data its comes false.

Small example for you.

<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }">
    <input id="passAnime" type="password" name="password" ng-model="user.password" class="form-control input-md" placeholder="Password" tabindex="5" ng-maxlength="25" ng-minlength="6" required>

    <span ng-show="userForm.password.$dirty && userForm.password.$invalid">
        <p ng-show="userForm.password.$error.required" class="error-messages">
             Your password is required.
        </p>
        <p ng-show="userForm.password.$error.minlength" class="error-messages">
            Your password is too short. Minimum 6 chars.
        </p>
        <p ng-show="userForm.password.$error.maxlength" class="error-messages">
            Your password is too long. Maximum 25 chars. 
        </p>
    </span>
</div>