<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS 输入验证</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<h2>用户注册</h2>
<form name="myForm" ng-submit="submitForm()" novalidate>
<label for="username">用户名:</label>
<input type="text" id="username" name="username" ng-model="user.username" required>
<div ng-show="myForm.username.$touched && myForm.username.$error.required">
<span style="color: red;">用户名是必填的。</span>
</div>
<br>
<label for="email">电子邮件:</label>
<input type="email" id="email" name="email" ng-model="user.email" required>
<div ng-show="myForm.email.$touched && myForm.email.$error.required">
<span style="color: red;">电子邮件是必填的。</span>
</div>
<div ng-show="myForm.email.$touched && myForm.email.$error.email">
<span style="color: red;">请输入有效的电子邮件地址。</span>
</div>
<br>
<label for="password">密码:</label>
<input type="password" id="password" name="password" ng-model="user.password" required>
<div ng-show="myForm.password.$touched && myForm.password.$error.required">
<span style="color: red;">密码是必填的。</span>
</div>
<br>
<button type="submit" ng-disabled="myForm.$invalid">提交</button>
</form>
<p ng-show="submitted">表单已提交!</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.user = {};
$scope.submitted = false;
$scope.submitForm = function () {
// 在这里可以添加处理提交表单的逻辑
console.log('用户提交的数据:', $scope.user);
$scope.submitted = true;
};
});
</script>
</body>
</html>
在这个例子中,我们使用了 required 和 email 等内置验证指令,同时通过 myForm.$invalid 来禁用提交按钮,以防止用户在表单中有错误时提交。
请注意,这只是一个简单的例子,实际应用中可能需要更多的验证规则和定制。
转载请注明出处:http://www.pingtaimeng.com/article/detail/4869/Angular