angularjs required validation using ng-pattern

angularjs required validation using ng-pattern

This code sample are used to validate a required field with single word which are given below.

Table of Contents.
  1. input type is equal to text [type="text"].
  2. ng-pattern with single word.
  3. Required element tag.
  4. ng-model with two way binding.
Example code

<!doctype html>
  <title> angularjs requiredvalidation </title>
  <script src=""></script>
    .error {
      color: red;
      var app = angular.module('myApp', []);

      app.controller('mainCtrl', function ($scope) {
          $scope.username = '';
          $scope.singleword = /^\s*\w*\s*$/;

<body ng-app="myApp">
  <ng-form name="myForm" ng-controller="mainCtrl">
    <div>UserName :</div>
      <input type="text" name="name" ng-model="username" ng-pattern="singleword" required>
      <span class="error" ng-show="$error.required">Required!</span>
      <span class="error" ng-show="$error.pattern">Only single word.</span>


The result look like below image.


Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
Post a Comment Powered by Blogger.
ASK Questions