Home » Angular JS » How to write a custom validator directive?

How to write a custom validator directive?

Assume that you have a form, in the form you have a text input which is allow you to input an url follow these rule

  • required (can not be empty)
  • accept a-z,A-Z,0-9 and the “_”
OK so how do we implement it?
firstly create a form with an input inside and a button to submit form

when you create a form like so angularjs automatically create an object with form’s name, let see how is the object look like:

as we see frmSurvey object has some elements such as: $error, $valid… and article_url (the input text),
article_url also is an object has some elements as: $valid, $modelValue, $viewValue $dirty
so now I want when I click Submit button I just need to check like so:

Let write a directive to validate for the input


pay attention on those lines below they are the most important part to add a validator to the form object

(the isExist validator part is just a bonus for unique check, check it out if you need otherwise you can ignore it)
1. set the validaty by ctrl.$setValidity(‘pattern’, true);
2. return ngModelValue; if we dont have this line the $modelValue of input text won have the value, but if you want you still can get the value by $viewValue
3. and finally add the doValid function to an array of other functions, if we don’t have this line nothing will be done

OK so now we have the directive let put it into the input tag

required: Sets required validation error key if the value is not entered.
check-valid-url: our custom validator

let’s see and test by yourself here https://jsbin.com/qisigav/edit?html,js,output

I found using directive is really used for reuse code and makes the code is so concise, beautiful.

thank you for your time.