Contact Number Validation In Angular

What is NG pattern?

The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.

The ng-pattern directive is used to validate the user input for the invalid characters with the help of Regular Expression patterns in AngularJS.

Syntax

<element ng-pattern="expression"> Contents... </element>

Below, I even have created a demonstration. We create HTML document and consist of reference of AngularJS document from CDN. We create ng-app, ng-controller, and inject module. We create Controller in JavaScript.
   
Step 1 
  
We create HTML document that consists of reference of AngularJS document from CDN.
   
Step 2 
  
Create ng-controller, and insert in web module. 
   
Step 3 
  
Create Controller in JavaScript. 
   
Step 4 
  
We use ng-sample for giving everyday expression. 
   
Step 5 

Create a span tag to show results or errors

So let's start with code example,

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope) { });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <form name="MyForm" ng-submit="MyForm.$valid" novalidate=novalidate>
        Mobile Number:
        <input type="text" ng-model="MobileNumber" name="MobileNumber" required="required"
               ng-pattern="/^(0|91)?[6-9][0-9]{9}$/" />
        <span class="error" ng-show="MyForm.MobileNumber.$error.required">Mobile Number is required.</span>
        <span class="error" ng-show="MyForm.MobileNumber.$error.pattern">Invalid Mobile Number.</span>
        <hr/>
        <button type="submit" ng-disabled="MyForm.$invalid">Submit</button>
    </form>
</div>
CSS Class
 
error – I will use Red for error output
<style type="text/css">
    body { font-family: Arial; font-size: 10pt; }
    .error { color: Red; }
</style>

OUTPUT


Similar Articles