如何在AngularJS中验证数据

如何在AngularJS中验证数据

在这篇文章中,我们将知道如何在Angular JS中验证数据,同时通过例子了解验证数据的各种方法。

AngularJS允许客户端表单验证。表单验证是必要的,因为它可以确保表单中的数据是正确的、完整的,并且是以正确的方式输入的,然后再提交表单并将详细信息发送到服务器。为了验证数据,我们需要同时验证表单和输入字段,并相应地通知用户当前的状态。如果用户以错误的格式输入数据,应该通知他,而不是提交错误的细节。

例如,如果要求用户输入电话号码,而用户输入的是 “abcde”,那么应该要求用户再次输入电话号码,并且应该通知用户在这个字段中只允许输入数字。通过在客户端执行表单验证,我们确保正确和完整的数据被发送到服务器。

有几个输入控件可以在AngularJS表单中使用,下面给出了这些控件。

  • input : 它用于从表单中获取各种类型的输入数据,如文本、密码、电子邮件等,通过改变其类型。
<input type="text" name="name">
  • select : 它用于创建一个下拉列表。
<select> 
 <option>1</option> 
 <option>2</option>
</select>
  • 按钮:它定义了一个可点击的按钮来控制其他元素或执行一个功能。
<button name="submit">Submit</button>
  • textarea : 它用于输入长文本内容。
<textarea name="teaxtarea"></textarea>

AngularJS包括以下验证指令。

  • ng-required : __它可以用来给一个输入字段加上必填属性。
  • ng-minlength : __它可以用来在输入字段上设置最小长度属性。
  • ng-maxlength : __它可以用来给输入字段加上最大长度属性。
  • ng-pattern : __如果ngModel值与RegEx表达式不匹配,它可以用来放置模式验证错误键。

实例1 :这个例子描述了使用验证指令进行表单验证的情况

<!DOCTYPE html>
<html>
  
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
</head>
  
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text" 
               ng-model="name" 
               name="name" 
               ng-minlength=3 
               ng-required="true" 
               ng-pattern="/^[\w\s]*/"> 
        <span ng-show="formname.name.error.minlength" 
              style="color:red">
            Minimum 3 characters required.
        </span> 
        <span ng-show="formname.name.error.pattern" 
              style="color:red">Name can have only alphabets.
        </span>
        <br>
        <label>Phone:</label>
        <input type="tel" 
               name="phone" 
               ng-model="phone" 
               ng-pattern="/^[0-9]*/" 
               ng-required="true" 
               ng-minlength=6 
               ng-maxlength=20> 
        <span ng-show="formname.phone.error.pattern" 
              style="color:red">Phone number can have only digits.
        </span> 
        <span ng-show="formname.phone.error.minlength" 
              style="color:red">Minimum 6 characters required.
        </span>
        <span ng-show="formname.phone.error.maxlength"
              style="color:red">Minimum 10 characters required.
        </span>
        <br>
        <label>Email:</label>
        <input type="email" 
               name="email" 
               ng-model="email" 
               ng-required="true" 
               ng-pattern=
"/^[a-zA-Z0-9.!#%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/">
            <span ng-show="formname.email.error.pattern" 
                  style="color:red">Email has to be in format abc@gmail.com.
        </span>
        <br>
        <label>Message:</label>
        <br>
        <textarea name="message" 
                  ng-model="message" 
                  ng-required="true" 
                  ng-maxlength=100></textarea> 
            <span ng-show="formname.message.$error.maxlength" 
                  style="color:red">Maximum length of message is 100 characters.
            </span>
    </form>
</body>
</html>

输出:

如何在AngularJS中验证数据?

示例1

解释:在上面的例子中,我们做了一个联系我们的表单。表格的名称是 “formname”。表格中有四个字:姓名、电话、电子邮件和信息。我们使用了验证指令来验证用户输入的数据。

对于名字,我们使用了ng-required指令,这意味着必须输入名字;ng-pattern指令有一个正则表达式,用于在名字中只允许输入字母和空格;ng-minlength指令用于确保名字至少有3个字符;ng-maxlength指令用于名字中允许的最大字符数。我们使用了ng-show指令来显示相应的信息。如果条件为真,ng-show指令会显示一条信息。例如,如果用户输入的名字不符合ng-pattern指令中指定的正则表达式formname.name.error.pattern “将为真,因此 “ng-show=formname.name.error.pattern “将打印消息 “Name can have only alphabets”。这里我们使用了$error对象,它包含应用于元素的验证属性。同样地,所有其他的字段:电话、电子邮件、信息都已被验证。

在AngularJS中,有两种验证数据的方法。第一种方法是使用验证控制状态,包括表单状态和输入状态。另一种方法是使用CSS类。

表单状态和输入状态:表单和输入字段的状态由AngularJS更新,这些状态被用来向用户显示有用的信息。

输入字段有以下状态。

  • $untouched : 该字段还未被触及。
  • $touched : 该领域已被触及
  • $pristine : 该字段没有被修改过
  • $dirty : 该字段已被修改
  • $valid : 该字段的内容是有效的
  • $invalid : 该字段内容无效

表格有以下状态。

  • $pristine : 没有字段被修改过
  • $dirty : 一个或多个字段已被修改
  • $invalid : 表单内容无效
  • $valid : 表格内容是有效的
  • $submitted : 该表格已提交

这些属性可以是真,也可以是假。

例子2:这个例子描述了使用表单和字段状态的表单验证。

<!DOCTYPE html>
<html>
  
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
</head>
  
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text" 
               ng-model="name" 
               name="name" 
               ng-required="true" 
               ng-pattern="/^[\w\s]*/">
         <span ng-show=
"formname.name.touched && formname.name.error.required " 
               style="color:red">
             Name is required and can have only alphabets.
         </span>
        <br>
        <label>Phone:</label>
        <input type="tel" 
               name="phone" 
               ng-model="phone" 
               ng-pattern="/^[0-9]*/" 
               ng-required="true"> 
            <span ng-show=
"formname.phone.invalid && formname.phone.touched" 
                  style="color:red">
                Phone number is required and can have only digits.
            </span>
        <br>
        <label>Email:</label>
        <input type="email" 
               name="email" 
               ng-model="email" 
               ng-required="true" 
               ng-pattern=
"/^[a-zA-Z0-9.!#%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/"> 
            <span ng-show=
"formname.email.invalid && formname.email.touched" 
                  style="color:red">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <label>Message:</label>
        <textarea name="message" 
                  ng-model="message" 
                  ng-required="true" 
                  ng-maxlength=100>
        </textarea> 
            <span ng-show=
"formname.message.invalid && formname.message.touched" 
                  style="color:red">
Message is required, maximum length of message can be 100 characters.
            </span>
        <br>
        <input type="submit" 
               name="submit" 
               ng-disabled="formname.$invalid"> 
    </form>
</body>
</html>

输出:

如何在AngularJS中验证数据?

解释:在上面的例子中,我们使用了字段状态进行验证。对于名字,我们使用了ng-show = “formname.name.touched && formname.name.error.required”,这意味着如果字段被触及,但字段仍然是空的,就会打印出 “名字是必需的,只能有字母 “的信息。

对于电话号码,我们使用了ng-show = “formname.phone.invalid && formname.phone.touched”,这意味着如果该字段被触及,并且用户输入的内容无效,那么将打印出所需的信息。同样地,我们已经验证了电子邮件和信息字段。

如果条件 “formname.$invalid “为真,我们就禁用这个按钮,这意味着如果表单中的任何字段有无效的数据,这个按钮就不会被启用。如果所有字段中输入的数据都是有效的,那么按钮将被启用。

用于表单验证的CSS类:为了让表单以及控件的风格化,ng-model添加了CSS类

以下类别被添加到输入栏或从输入栏中删除。

  • ng-untouched : 字段还未被触及
  • ng-touched : 领域已被触及
  • ng-pristine : 字段没有被修改过
  • ng-dirty : 字段已被修改
  • ng-valid :字段内容是有效的
  • ng-invalid :字段内容是无效的

以下类别被添加到表格或从表格中删除。

  • ng-pristine : 没有字段尚未被修改
  • ng-dirty : 一个或多个字段被修改了
  • ng-valid : 表格内容是有效的。
  • ng-invalid : 表单内容是无效的

例子3:在这个例子中,我们使用CSS类为表单和字段添加样式。

<!DOCTYPE html>
<html>
  
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
    <style>
        input.ng-invalid,
        textarea.ng-invalid {
            background-color: red;
        }
          
        input.ng-untouched,
        textarea.ng-untouched input.ng-pristine,
        textarea.ng-pristine {
            background-color: pink;
        }
          
        input.ng-touched,
        textarea.ng-touched {
            background-color: red;
        }
          
        input.ng-valid,
        textarea.ng-valid {
            background-color: green;
        }
          
        form {
            padding: 40px;
        }
          
        form.ng-invalid {
            background-color: #ed98a5;
        }
          
        form.ng-valid {
            background-color: #98edaf;
        }
    </style>
</head>
  
<body ng-app="">
    <h1>Contact Us</h1>
    <form name="formname">
        <label>Name:</label>
        <input type="text" 
               ng-model="name" 
               name="name" 
               ng-minlength=3 
               ng-required="true" 
               ng-pattern="/^[\w\s]*/">
            <span ng-show=
"formname.name.error.minlength" 
                  style="color:red">
               Minimum 3 characters required.
            </span>
            <span ng-show=
"formname.name.error.pattern"
                  style="color:red">
               Name can have only alphabets.
            </span>
        <br>
        <label>Phone:</label>
        <input type="tel" 
               name="phone" 
               ng-model="phone" 
               ng-pattern="/^[0-9]*/" 
               ng-required="true" 
               ng-minlength=6 
               ng-maxlength=20> 
            <span ng-show=
"formname.phone.error.pattern" 
                  style="color:red">
                Phone number can have only digits.
            </span> 
            <span ng-show=
"formname.phone.error.minlength"
                  style="color:red">
                Minimum 6 characters required.
           </span>
           <span ng-show=
"formname.phone.error.maxlength" 
                 style="color:red">
                Minimum 10 characters required.
           </span>
        <br>
        <label>Email:</label>
        <input type="email" 
               name="email" 
               ng-model="email" 
               ng-required="true" 
               ng-pattern=
"/^[a-zA-Z0-9.!#%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*/"> 
            <span ng-show=
"formname.email.error.pattern" 
                  style="color:red">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <label>Message:</label>
        <br>
        <textarea name="message" 
                  ng-model="message" 
                  ng-required="true"
                  ng-maxlength=100>
        </textarea> 
            <span ng-show=
"formname.message.$error.maxlength" 
                  style="color:red">
                Maximum length of message is 100 characters.
            </span> 
    </form>
</body>
</html>

输出 :

如何在AngularJS中验证数据?

解释:在上面的例子中,我们使用了CSS类来为输入控件和表单添加样式。最初,表单的颜色是红色。对于输入字段,如果用户输入的数据是无效的,输入控件的颜色将变为红色。如果用户没有触摸或修改该字段,其颜色将保持为粉红色。如果用户触碰了该字段,但没有输入任何东西,其颜色将变为红色。如果用户输入的数据是有效的,其颜色将变为绿色。当所有的字段都有有效的数据时,表格的颜色会变成绿色。

例子4:在这个例子中,我们通过指定不同的验证检查来创建注册表。

<!DOCTYPE html>
<html>
  
<head>
    <title>Data Validation in Angular JS</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
  <style>
        input.ng-dirty {
            background-color: lightblue;
        }
          
        input.ng-valid {
            background-color: lightgreen;
        }
          
        span,
        p {
            color: red;
        }
          
        table {
            border-collapse: collapse;
            margin-bottom: 20px;
            margin-top: 10px;
        }
          
        tr,
        td,
        th {
            border: 1px solid black;
        }
    </style>
</head>
  
<body ng-app="myApp" 
      ng-controller="myctrl">
    <h1>Registration Form</h1>
    <form name="formname">
        <label>First Name:</label>
        <input type="text" 
               ng-model="firstname" 
               name="firstname" 
               ng-minlength=3 
               ng-required="true" 
               ng-pattern="/^[\w\s]*/">
            <span ng-show=
"formname.firstname.touched && formname.firstname.error.required">
                Name is required.
            </span> 
            <span ng-show=
"formname.firstname.error.minlength">
                Minimum 3 characters required.
            </span>
            <span ng-show=
"formname.firstname.error.pattern">
                Name can have only alphabets.
            </span>
        <br>
        <label>Last Name</label>
        <input type="text" 
               ng-model="lastname" 
               name="lastname" 
               ng-minlength=3 
               ng-required="true" 
               ng-pattern="/^[\w\s]*/"> 
            <span ng-show=
"formname.lastname.touched && formname.lastname.error.required">
                Name is required.
            </span> 
            <span ng-show=
"formname.lastname.error.minlength">
                Minimum 3 characters required.
            </span> 
            <span ng-show=
"formname.lastname.error.pattern">
                Name can have only alphabets.
            </span>
        <br>
        <label>Gender:</label>
        <br>
        <input type="radio" 
               name="gender" 
               ng-model="gender" 
               value="Male" 
               ng-required="true">
        <label>Male</label>
        <input type="radio" 
               name="gender" 
               ng-model="gender" 
               value="Female" 
               ng-required="true">
        <label>Female</label>
        <br>
        <label>Password</label>
        <input type="password" 
               name="password" 
               ng-model="password" 
               ng-required="true" 
               ng-minlength=6 
               ng-maxlength=10> 
            <span ng-show=
"formname.password.touched && formname.password.error.required">
                Password is required.
            </span>
            <span ng-show=
"formname.password.error.minlength">
                Minimum 6 characters required.
            </span> 
            <span ng-show=
"formname.password.error.maxlength">
                Minimum 10 characters required.
            </span>
        <br>
        <label>Phone</label>
        <input type="tel" 
               name="phone" 
               ng-model="phone" 
               ng-pattern="/^[0-9]*/" 
               ng-required="true" 
               ng-minlength=6 
               ng-maxlength=10>
            <span ng-show=
"formname.phone.touched && formname.phone.error.required">
                Phone is required.
            </span> 
            <span ng-show="formname.phone.error.minlength">
                Minimum 6 characters required.
            </span> 
            <span ng-show=
"formname.phone.error.pattern">
                Phone number can have only digits.
            </span> 
            <span ng-show=
"formname.phone.error.maxlength">
                Minimum 10 characters required.
            </span>
        <br>
        <label>Email:</label>
        <input type="email" 
               name="email" 
               ng-model="email" 
               ng-required="true" 
               ng-pattern="/^[a-z0-9/_#%]+@[a-z]+[.]+[a-z]+/"> 
            <span ng-show=
"formname.email.touched && formname.email.error.required">
                Email is required.
            </span> 
            <span ng-show=
"formname.email.error.pattern">
                Email has to be in format abc@gmail.com.
            </span>
        <br>
        <select ng-model="city" 
                name="city" 
                ng-required="true">
            <option disabled="">Select city</option>
            <option ng-repeat="x in citylist">{{x}}</option>
        </select>
        <span ng-show=
"formname.city.error.required">
            Select a city
        </span>
        <br>
        <label>Select technologies</label>
        <br>
        <input type="checkbox" 
               name="option1" 
               ng-model="checkboxvalue1" 
               value="HTML">
        <label>HTML</label>
        <br>
        <input type="checkbox" 
               name="option2" 
               ng-model="checkboxvalue2" 
               value="CSS">
        <label>CSS</label>
        <br>
        <input type="checkbox" 
               name="option3" 
               ng-model="checkboxvalue3" 
               value="JavaScript">
        <label>JavaScript</label>
        <br>
        <input type="checkbox" 
               name="option4" 
               ng-model="checkboxvalue4" 
               value="PHP">
        <label>PHP</label>
        <br>
        <p ng-if=
'!checkboxvalue1 && !checkboxvalue2 && !checkboxvalue3 && !checkboxvalue4'>
                Select a technology
        </p>
  
        <input type="submit" 
               name="submit" 
               ng-click="calculate()" 
               ng-disabled="formname.invalid">
    </form>
    <br>
    <table>
        <tr ng-repeat="x in list"
            ng-show="value!=0">
            <td>{{x.key}}</td>
            <td>{{x.value}}</td>
        </tr>
    </table>
    <script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('myctrl', function(scope) {
            scope.value = 0;
            scope.firstname = '';
            scope.city = "Select city";
            scope.citylist = ["Mumbai", "Jaipur", "Pune"];
            scope.calculate = function() {
                scope.value += 1;
                scope.list1 = [];
                if(scope.checkboxvalue1) 
                    scope.list1.push(formname.option1.value);
                if(scope.checkboxvalue2) 
                    scope.list1.push(formname.option2.value);
                if(scope.checkboxvalue3) 
                    scope.list1.push(formname.option3.value);
                if(scope.checkboxvalue4) 
                    scope.list1.push(formname.option4.value);
                scope.list2 = scope.list1.toString();
                scope.list = [{
                    "key": "First name",
                    "value": scope.firstname
                }, {
                    "key": "last name",
                    "value":scope.lastname
                }, {
                    "key": "Gender",
                    "value": scope.gender
                }, {
                    "key": "Phone",
                    "value":scope.phone
                }, {
                    "key": "Email",
                    "value": scope.email
                }, {
                    "key": "City",
                    "value":scope.city
                }, {
                    "key": "Selected Technologies",
                    "value": $scope.list2
                }];
            }
        });
    </script>
</body>
</html>

输出:

如何在AngularJS中验证数据?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程