AngularJS ngpattern
- The ng-pattern in AngularJS used for add up the pattern validator to ngModel.
- It is mainly used for text-based input controls but also applied for custom text-based controls.
- It is used for sets the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression given in the ngpattern attribute value:
- It is used directly when the expression evaluates to a RegExp object.
- Whenever the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.
- For ex, "abc" will be converted to new RegExp ('^abc$').
Syntax for ng-pattern directive in AngularJS:
Sample coding for ng-pattern directive in AngularJS:
ng-pattern directive in AngularJS:
Code Explanation for ng-pattern directive in AngularJS:
- The ng-appspecifies the root element (“myApp”) to define AngularJS application.
- The ng-controllercontrol the data of “patternCtrl” in AngularJS application.
- The “number” is declare the type name in <input> tag.
- The ng-modelbind an input field value to AngularJS application variable (“number”).
- The “ng-pattern” is used to specify the textbox should match the pattern specified in the regex.
- The <span> is used to display the warning on the required field error.
- The <span> is used to display the warning on pattern error.
- The “submit”is declare the typevalue of the <input> tag.
Sample Output for ng-pattern directive in AngularJS:
- If the textbox is empty, then the required field error shows the warning.
- If the user enters valid mobile number, there is no warning displayed.
- If the textbox does not match the pattern, then the pattern error shows the warning.
Tips and Notes
The ng-pattern directive is added when the plain pattern attribute is used, with two differences:
- The ng-pattern directive does not set the pattern attribute.
- The ngpattern attribute should be an expression, while the pattern value must be inserted