0

I am trying to validate input to a form before passing it to the server but it doesn't seem to check the input field, and doesn't report an error. my directive code to create a custom validator:

`var QUERY_REGEXP = /[A-Z,a-z,0-9]{1,20}/;
 app.directive('q', function() {
 return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
  ctrl.$validators.q = function(modelValue, viewValue) {
    if (ctrl.$isEmpty(modelValue)) {

      return true;
    }

    if (QUERY_REGEXP.test(viewValue)) {

      return true;
    }

    return false;
  };
  }
 };
});` 

html for the same:

    <div ng-controller="CreditsController">     
    <div style="padding-top:20px" >
    <form name='form' novalidate>
    <b>Enter Name:&nbsp;&nbsp;</b><input id="creditq" ng-model='query1' name='query1' type="text" q />
    <button id="Submit" ng-click='click()' ng-value='search' required>Search</button><br/><br/>
    <span ng-show="form.query1.$error.query1">The value is not valid!</span>
    </form>
    </div>

I can't figure out what I'm missing or doing wrong. Any help would be appreciated.

2
  • Is it getting into the $validators.q function at all, or just not displaying the error? Commented May 20, 2015 at 21:18
  • I got it to work. There was a coding error which was pointed out to me by @bgoscinski. thanks Commented May 22, 2015 at 17:03

1 Answer 1

0

I can see few problems here:

  • regexp: /[A-Z,a-z,0-9]{1,20}/ will match any string which consists of upper and lower cased letters, digits and a coma. {1,20} is not going to help here because you didn't specify that it have to fit between begin and end of the whole string. I think your regexp should be: /^[A-Za-z0-9]{1,20}$/

  • According to this

    As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

    So you have two options: recreate regexp on every validator call or reset lastIndex property to 0 on every call.

  • Your validator is named q so

    <span ng-show="form.query1.$error.query1">The value is not valid!</span>

    Will never show because $error will never have query1 property. It will be named q as your validator.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pointing the problems I had, it seems to work fine when I type it out in the input field, though I wanted it to validate upon clicking submit so that the value doesn't pass through. Any way I can do this?
If by pass through you mean that you want your form not to be submitted unless validation succeed you can check form.$valid or form.$invalid property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.