jubi jubi -4 years ago 110
AngularJS Question

how to add pattern validation in angular

I am having a model with a float propert

public float Amount { get; set; }

and a text box to display anf edit the value of amount.

only number accepted

my text box should allow characters and on while entering it should show error message

here i want to add a validation to restrict only number and decimal point.
here my validation is not working when i enter characters in the text box.

When i checked i can see that upon entering characters on text box {{model.amount}} is turned to blank . I think this is the problem. Can someone suggest what to do in this scenario

Answer Source

You Can add ng-patter or add html5 input type number with step attr.


<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal" *step="0.01"* />


<form name="myForm">
  <input type="text" name="test1"  data-ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" data-ng-model="model.amount" /> 
  <span data-ng-show="myForm.test1.$error.pattern">invalid</span> 

Please check working Ex. here https://plnkr.co/edit/WSqMHsLSCkRk7VVsNfHQ?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download