Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Say I have an input that specifies a pre existing validator

ng-pattern="stringValidator"

and I want to extend or customize this pattern without creating a whole new pattern, is there way to do that inline? In other words can I enter the validation regex directly into the tag declaration or something similiar that?

Current Tag Declaration:

The "stringValidator" pattern, which is defined externally to this code domain, impliments an undesirable rule which I need to override. I can not edit "stringValidator", nor can I add a custom rule to the same code file as "stringValidator".

<input type="text" id="txt-foo" placeholder="" name=""
               class="form-control"
               ng-model="txtName" ng-maxlength="255"
               ng-pattern="stringValidator"
               autocomplete="off" />

I would like to do something like this:

<input type="text" id="txt-foo" placeholder="" name=""
               class="form-control"
               ng-model="txtName" ng-maxlength="255"
               ng-pattern="/^[^%\[\]<>"%;&()]+$/"
               autocomplete="off" />

Thanks.

share|improve this question

1 Answer 1

It should just work as expected, but your pattern will be broken by the browser as your pattern literal will be terminated prematurely due to the presence of " in the pattern and value is wrapped in " as well. So wrap the pattern in single quotes or escape quotes with &quot; in the attribute value (it will be automatically un-escaped when browser renders).

i.e ng-pattern='/^[^%\[\]<>"%;&()]+$/'

Or

ng-pattern="/^[^%\[\]<>&quot;%;&()]+$/"

Do remember to use name for your input as well, because without a name for the control, form controller will not be able to associate properties to its instance.

Working Demo

input.ng-invalid {
  border-width: 2px 5px 2px 2px;
  border-style: solid;
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <form name="form">
    <input type="text" id="txt-foo" placeholder=""  class="form-control" ng-model="txtName" ng-maxlength="255" ng-pattern="/^[^%\[\]<>&quot;%;&()]+$/" autocomplete="off" />
  </form>

</div>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.