domoindal domoindal - 4 months ago 13
AngularJS Question

AngularJS validation errors

I have a working form with ngMessages.

My issue is that when displayed the form and then empty, i do not want to show errors, only when the user has focused out the input.

Is this possible?

Answer

Use $touched:

Snippet:

var app = angular.module('app', ['ngMessages']);

app.controller('mainCtrl', function($scope) {
  // Any JS Code
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://code.angularjs.org/1.5.7/angular.js"></script>
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
  <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
  <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
  <script src="https://code.angularjs.org/1.4.7/angular-messages.js"></script>
</head>

<body ng-controller="mainCtrl">
  <form role="form" name="form" novalidate>
    <div class="col-md-12">
      <div class="form-group" ng-class="{ 'has-error' : form.email.$touched && form.email.$invalid }">
        <label>Name</label>
        <input type="email" name="email" class="form-control" placeholder="Name" ng-model="email" required>
        <div class="help-block" ng-messages="form.email.$error" ng-if="form.email.$touched">
          <p ng-message="required">This field is required</p>
          <p ng-message="minlength">This field is too short</p>
          <p ng-message="maxlength">This field is too long</p>
          <p ng-message="required">This field is required</p>
          <p ng-message="email">This needs to be a valid email</p>
        </div>
      </div>
    </div>
  </form>
</body>

</html>

For more check here.

I hope it helps!