Hi Guys,

AngularJS has given provision for user to create custom validation on form and this can be achieved by using $validators of ngModel.NgModelController.

From AngularJS doc
$validators :
A collection of validators that are applied whenever the model value changes. The key value within the object refers to the name of the validator while the function refers to the validation operation. The validation operation is provided with the model value as an argument and must return a true or false value depending on the response of that validation.


index.html
<div ng-controller="DemoController">
 <form novalidate name="form">
  <input name="user" type="text" ng-validation ng-model="user">
  <span ng-show="form.$submitted && form.user.$error.testing" class="error">
    Please enter 'testing' as text
  </span>
  <br/>
  <input type="submit" value="Submit"/>
 </form>
</div>

Over here we have added ng-validation, a custom directive where we have access to ngModel's controller.

app.js
app.directive("ngValidation", function(){
 return{
  restrict:"A",
  require:"ngModel",
  link:function(scope, element, attrs, ctrls){
   ctrls.$validators.testing = function(value){
    if(value=="testing"){
     return true;
    }
    return false
   }
  }
 }
});

Now ngModel controller have $validators property in which we can add our own validation. Over here I am just validating with a string. i.e. if the input string matches with "testing" word it will return true else false.

Below is the reference of object model of input field where you can find testing as a validation been added in $error property.




















Plunker: https://plnkr.co/edit/IEzTtcWtYSnlbAJlQEvj?p=preview

Good Day :)