angular.js如何验证本例中的表单

How does angular.js validate the form in this example?

本文关键字:表单 验证 js 何验证 angular      更新时间:2023-09-26

我正在看这个页面上的示例:http://www.w3schools.com/angular/tryit.asp?filename=try_ng_validate

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</head>
<body>
    <h2>Validation Example</h2>
    <form ng-app="" 
          ng-controller="validateCtrl" 
          name="myForm" 
          novalidate>
    <p>Username:<br>
    <input type="text" 
           name="user" 
           ng-model="user" 
           required>
    <span style="color:red" 
           ng-show="myForm.user.$dirty && myForm.user.$invalid">
        <span ng-show="myForm.user.$error.required">
            Username is required.
         </span>
    </span>
    </p>
    <p>Email:<br>
    <input type="email" 
           name="email" 
           ng-model="email"  
           required>
    <span style="color:red" 
          ng-show="myForm.email.$dirty && myForm.email.$invalid">
        <span ng-show="myForm.email.$error.required"> 
            Email is required.
        </span>
        <span ng-show="myForm.email.$error.email">
            Invalid email address.
        </span>
    </span>
    </p>
    <p>
    <input type="submit"
           ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||  
                        myForm.email.$dirty && myForm.email.$invalid">
    </p>
    </form>
<script>
function validateCtrl($scope) {
    $scope.user = 'John Doe';
    $scope.email = 'john.doe@gmail.com';
}
</script>
</body>
</html>

我不明白的是,似乎没有验证代码。我特别不明白为什么下面的行有效:

<span ng-show="myForm.email.$error.email">Invalid email address.</span>

但是,如果我放置类似的行来尝试假装用户名是一个电子邮件地址,它会忽略它。即,以下内容不会检查用户名是否是电子邮件地址:

<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
<span ng-show="myForm.user.$error.email">Invalid email address.</span>
</span>
</p>

有人能更好地解释一下吗?

这是因为您的email文件是email的类型,所以它会根据email格式进行验证。并且您的用户名只是一个text文件,因此angular将仅针对text输入而不是针对email 进行验证

这是一个简单的演示

在您的情况下,电子邮件字段是必需的,并且应该是一封电子邮件,

<input type="email" name="email" ng-model="email" required>

因此angular将首先检查其是否为空,如果不是,则将检查该值是否为email

但在文本字段只是一个文本

因此angular将只检查文本框值是否为空