runningmark
runningmark

Reputation: 760

custom validation in angular

I'm new to angular and I'm unable to find perfect solution for custom validation for angular application.

We have an input field which is attached to array(list has 2500+ options) now we want to validate for the value user typed against the array which we are unable to do, here is our simple code

    var value_array = ["a",c","c"];
    app.directive('validValue', function() {
        return {
            restrict: 'A',
            require: '^form',
            link: function(scope,elem,attr,formController) {
                elem.bind('blur', function() {
                 // no idea what to do from here
        }
    });

Upvotes: 0

Views: 211

Answers (1)

Mohamed El-Sayed
Mohamed El-Sayed

Reputation: 501

You can use a datalist element to validate against, or use setCustomValidity to invalidate the element.

Using datalist in template(may not require a directive):

<input ng-model="model" list="validOptions">
<datalist id="validOptions">
  <option value="red" />
  <option value="green" />
  <option value="blue" />
</datalist>

Using setCustomValidity:

to mark the element as valid, pass an empty string '' to the function, otherwise pass the error message.

elem.bind('blur', function() {
  for(let validOption of options) {
    if(validOption === value) {
      return elem[0].setCustomValidity('');
    }
  }
  elem[0].setCustomValidity('Invalid value, try again');
});

Upvotes: 1

Related Questions