0

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
        }
    });

1 Answer 1

1

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');
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.