In this article, we will learn about how we can validate a form in AngularJS.

AngularJS offers client-side form validation.

Example

Open the Example1.html file and add the code in it.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <title></title>
    <style>
        .labelWarning {
            color: #FF0000;
        }
    </style>
</head>
<body ng-app="">
    <h2>Form Validation In AngularJS</h2>
    <form name="myForm">
        <table>
            <tr>
                <td>User Name</td>
                <td>
                    <input name="txtName" ng-model="txtName" required>
                    <span class="labelWarning" ng-show="myForm.txtName.$touched && myForm.txtName.$invalid">User Name is required.</span>
                </td>
            </tr>
            <tr>
                <td>Email</td>
                <td>
                    <input type="email" name="txtEmail" ng-model="txtEmail" required>
                    <span class="labelWarning" ng-show="myForm.txtEmail.$touched && myForm.txtEmail.$invalid">
                        <span ng-show="myForm.txtEmail.$error.required">Email is required.</span>
                        <span ng-show="myForm.txtEmail.$error.email">Invalid Email address.</span>
                    </span>
                </td>
            </tr>
            <tr>
                <td>Mobile Number</td>
                <td>
                    <input type="text" name="txtMobile" ng-model="txtMobile" ng-pattern="/^[0-9]{10,10}$/" maxlength="10" required>
                    <span class="labelWarning" ng-show="myForm.txtMobile.$touched && myForm.txtMobile.$invalid">
                        <span ng-show="myForm.txtMobile.$error.required">Mobile Number is required.</span>
                        <span ng-show="myForm.txtMobile.$error.pattern">Mobile Number should be 10 digits.</span>
                    </span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td><br /><input type="submit" ng-disabled="myForm.$invalid"></td>
            </tr>
        </table>
    </form>
</body>
</html>
  • The HTML5 required attribute, to specify that the input field must be filled out.
  • The AngularJS $touched state returns true if a control has lost focus.
  • The AngularJS $invalid state returns true if the model is invalid.
  • The AngularJS $error object contains all the validation attributes applied to the specified control.
  • The AngularJS ng-pattern directive is used to add up a regex pattern validator to ngModel on <input> element.
  • The HTML5 maxlength attribute, to specifies the maximum number of characters allowed in the <input> element.
  • The AngularJS $invalid state returns true if the form content is not valid.

Output:

 

Also, check How To Call API In AngularJS