[英]How does angular.js validate the form in this example?
我正在查看此頁面上的示例: 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將僅檢查文本框值是否為空
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.