NOCARRIER
NOCARRIER

Reputation: 2634

Angular JS - string patterns with custom validation rules

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.

Upvotes: 0

Views: 649

Answers (1)

PSL
PSL

Reputation: 123739

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>

Upvotes: 1

Related Questions