Please let me know " /> Please let me know " /> Please let me know "/>

To allow only one numeric value in text box based on regular expression in AngularJs

634 Views Asked by At

I'm using ng-pattern :

 <input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^[4]*$/" required only-digits>

Please let me know what to do that it does not accept any other numbers except 4. I am using directive for digits that is only-digits.

3

There are 3 best solutions below

0
Anton Skybun On

EDIT: SORRY WRONG ANGULAR VERSION - but if you can transform this to angularjs it will be work!

You can use (input) event in you HTML input element

<input type="number" (input)="check($event)">

Than in your ts you cehck value of input

  check(event) {
    console.log(event);
    if (+event.data !== 4) {
      event.target.value = '';
    }
  }
1
Ethiraj On

The pattern which you are mentioned is not a valid regex pattern. Instead of that try to use this /^([4]){1}?$/ Hope you will get it.

 <input type="text" ng-model="price" name="price_field" ng-pattern-restrict="/^([4]){1}?$/" required only-digits>
1
Hasta Dhana On

Try to use below restrict pattern :

<input type="text" ng-model="price" name="price_field" ng-pattern-restrict="^[4]{1}?$" required only-digits>

And below validation message :

<div ng-messages="myForm.price_field.$error">
    <span ng-message="pattern">Not a valid number!</span>
</div>