2

I want validate a form where for each input may have many error messages as per input. I want to write those error message from javaScript.

HTML

<input name="username" ng-model="user.username" type="text" placeholder="Username" required>
<div class="field-message" ng-messages="frm.username.$error" ng-if='frm.username.$dirty' ng-cloak>
     <div ng-message="required">Username is required</div>
</div>

JS

angular.module('DemoApp', ['ngMessages']);    
angular.bootstrap(document.getElementById('demoApp'), ['DemoApp']);

In the above code ng-message directive have error message that will be shown if input is not valid. If there are so many case to validate and each case have different error message then multiple ng-message have to add in html for particular input control.

I want to only input tag in html and error message to be come from javascript.

How can I achieve this?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Praveen D
  • 2,258
  • 2
  • 23
  • 40

1 Answers1

2

See this question: How to add custom validation to an AngularJS form?

To summarize:

You can use ui-validate

OR

You can just create custom validation, like so (copied from the answer in the original question):

app.directive('blacklist', function (){ 
   return {
      require: 'ngModel',
      link: function(scope, elem, attr, ngModel) {
          var blacklist = attr.blacklist.split(',');

          //For DOM -> model validation
          ngModel.$parsers.unshift(function(value) {
             var valid = blacklist.indexOf(value) === -1;
             ngModel.$setValidity('blacklist', valid);
             return valid ? value : undefined;
          });

          //For model -> DOM validation
          ngModel.$formatters.unshift(function(value) {
             ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
             return value;
          });
      }
   };
});

And here's some example usage:

<form name="myForm" ng-submit="doSomething()">
   <input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
   <span ng-show="myForm.fruitName.$error.blacklist">
      The phrase "{{data.fruitName}}" is blacklisted</span>
   <span ng-show="myForm.fruitName.$error.required">required</span>
   <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

EDIT: According to OP's request, print only the relevant error:

Plunkr: http://plnkr.co/edit/KN0Oukb8uACvZjtGPUg4?p=preview

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.doSomething = function() {
    alert('Submitted!');
  }

  $scope.getErrors = function() {
    if ($scope.myForm.fruitName.$error.required) {
      return 'This field is required';
    } else if ($scope.myForm.fruitName.$error.blacklist) {
      return 'The phrase ' + $scope.data.fruitName + ' is blacklisted';
    }
  }
});

app.directive('blacklist', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attr, ngModel) {
      var blacklist = attr.blacklist.split(',');
      ngModel.$parsers.unshift(function(value) {
        ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
        return value;
      });
    }
  };
});
.invalid {
  color: red;
}
.ng-invalid {
  border-color: red;
}
<!DOCTYPE html>
<html ng-app="angularjs-starter">
    <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
    <form name="myForm" ng-submit="doSomething()">
       <div>Please <u>don't</u> type the words: coconuts, bananas or pears.</div>
       <input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
       <span class="invalid" ng-show="myForm.fruitName.$error">{{getErrors()}}</span>
       <br/>
       <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
       <button type="button" ng-click="getErrors()">Get errors</button>
    </form>
  </body>
</html>
Community
  • 1
  • 1
Noy
  • 1,248
  • 2
  • 11
  • 28
  • Here you added two span for two error message. if there are 100 then we have to add 100 span with ng-show directive. that is not good. so I want only one span that will hold error message, and error message should be place from JavaScript file. – Praveen D Feb 16 '16 at 12:09
  • You can use `ng-messages-include` to include your all 100 message. You can define this 100 message in the separate file and then include then. – Stepan Kasyanenko Feb 16 '16 at 12:21
  • @PraveenD you can always have a function in the controller with and parse myForm.fruitName.$error - then you can print out just the relevant error – Noy Feb 16 '16 at 13:37
  • thank you for the answer. Are you suggesting like myForm.fruitName.$error = "Fruit name is invalid."; like that we can set error message from js. Can you please share any example of this if possible. – Praveen D Feb 17 '16 at 06:51