user636525
user636525

Reputation: 3200

Validate Input fields only on submit angularjs

I am trying to show a Validation Summary, a Div on top of the page with all the Validation error messages in angularjs, on form submit. I am using the below logic to show/ hide the top div with validation messages,

<div class="alert alert-error" ng-show="submitted && myForm.$invalid">
</div>

I am setting the variable submitted to true on save button click. It's working Okay the first time, but after the first submission, if enter the value for the input field(required field) and clear it, it's kicking off the validation(the top div shows).

Is there a way to show the validation div, only on the submit of the form and not when the user clears the input field ?

UPDATE

$scope.save = function (myForm) {

    $scope.submitted = true;

    if (myForm.$invalid) {
        return;
    }

    $scope.submitted = false;
}

Thanks !

Upvotes: 1

Views: 3817

Answers (2)

ryeballar
ryeballar

Reputation: 30098

Hmm one way to do it would be to watch the FormController's property $dirty and $setPristine() method, and use a variable hasError to show the error or not.

See this plunker as an example

JAVASCRIPT

controller('AppController', ['$scope', function($scope) {

  $scope.hasError = false;

  $scope.$watch('theForm.$dirty', function() {
    $scope.hasError = false;
    $scope.theForm.$setPristine();
  });

  $scope.save = function() {
    $scope.hasError = $scope.theForm.$invalid;

    if($scope.hasError) {
      // perform error routine
    } else {
     // perform save routine
    }
  };

}]);

HTML

   <body ng-controller="AppController">

    <div class="error" ng-show="hasError">This is an error</div>

    <form name="theForm" ng-submit="save()" novalidate>
      <input type="text" name="text1" ng-model="text1" required>
      <input type="text" name="text2" ng-model="text2" required>
      <button type="submit">Submit</button>
    </form>

  </body>

Upvotes: 0

Darren
Darren

Reputation: 79

Make sure you are setting submitted to false upon display of your validation div else it'll show up after each additional validation call.

    $scope.save = function (myForm) {

        $scope.submitted = true;

            if (myForm.$invalid) {
                    $scope.submitted = false;
                    return;
            }
    }

Upvotes: 0

Related Questions