angularjs – 仅在提交或用户输入时验证表单字段
发布时间:2020-12-17 09:00:14 所属栏目:安全 来源:网络整理
导读:我有使用required验证的表单字段。问题是,在呈现表单时立即显示错误。我想要它只显示在用户实际输入文本字段后,或提交。 如何实现这个? 使用$ dirty标志仅在用户与输入交互后显示错误: div input type="email" name="email" ng-model="user.email" requi
我有使用required验证的表单字段。问题是,在呈现表单时立即显示错误。我想要它只显示在用户实际输入文本字段后,或提交。
如何实现这个?
使用$ dirty标志仅在用户与输入交互后显示错误:
<div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span> </div> 如果只想在用户提交表单后触发错误,可以使用单独的标志变量,如: <form ng-submit="submit()" name="form" ng-controller="MyCtrl"> <div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required"> Email is required </span> </div> <div> <button type="submit">Submit</button> </div> </form> function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } }; 然后,如果所有在ng-showexpression中的JS看起来太多了,你可以将它抽象为一个单独的方法: function MyCtrl($scope){ $scope.submit = function(){ // Set the 'submitted' flag to true $scope.submitted = true; // Send the form to server // $http.post ... } $scope.hasError = function(field,validation){ if(validation){ return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]); } return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid); }; }; <form ng-submit="submit()" name="form"> <div> <input type="email" name="email" ng-model="user.email" required /> <span ng-show="hasError('email','required')">required</span> </div> <div> <button type="submit">Submit</button> </div> </form> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |