如何简化表单验证? [英] How can I simplify form validation?

查看:25
本文介绍了如何简化表单验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码似乎可以很好地进行基本的必需表单验证.

当字段脏+无效时,表单显示红色Name is required消息,如果字段脏+有效,则显示Great!消息.

但是为表单中的每个字段重复此代码是一团糟:

<div class="控制组"ng-class="{error: myForm.name.$invalid && myForm.name.$dirty}"><标签>名称:</label><input type="text" name="name" ng-model="user.name" required/><span ng-show="myForm.name.$invalid && myForm.name.$dirty"class="help-inline">名称为必填项</span><span ng-show="myForm.names.$valid && myForm.names.$dirty">太棒了!</span>

</表单>

我希望能够以更简单的方式指定 ng-showng-class 属性.

解决方案

一种方法是将验证表达式抽象为作用域方法:

PLUNKER

HTML

<标签>名称:</label><input type="text" name="name" placeholder="Name" ng-model="user.name" required/><span ng-show="isInvalid('name')" class="help-inline">名称是必需的</span><span ng-show="isValid('name')">太棒了!</span>

控制器

function Ctrl($scope) {$scope.isInvalid = 函数(字段){返回 $scope.myForm[field].$invalid &&$scope.myForm[field].$dirty;};$scope.isValid = 函数(字段){返回 $scope.myForm[field].$valid &&$scope.myForm[field].$dirty;};}

The code below seems to work pretty well for doing basic required form validation.

The form displays a red Name is required message when the field is dirty + invalid and a Great! message if the field is dirty + valid.

But it's a mess having repeat this code for each and every field in the form:

<form name="myForm">
    <div class="control-group" 
     ng-class="{error: myForm.name.$invalid && myForm.name.$dirty}">
        <label>Name:</label>
        <input type="text" name="name" ng-model="user.name" required/>
        <span ng-show="myForm.name.$invalid && myForm.name.$dirty" 
            class="help-inline">Name is required</span>
        <span ng-show="myForm.names.$valid && myForm.names.$dirty">Great!</span>
    </div>
</form>

I would like to be able to specify the ng-show and ng-class attributes in some easier way.

解决方案

One way you could do it is to abstract your validation expression to scope methods:

PLUNKER

HTML

<div class="control-group" ng-class="{error: isInvalid('name')}">
  <label>Name:</label>
  <input type="text" name="name" placeholder="Name" ng-model="user.name" required/>
  <span ng-show="isInvalid('name')" class="help-inline">Name is required</span>
  <span ng-show="isValid('name')">Great!</span>
</div>

Controller

function Ctrl($scope) {
  $scope.isInvalid = function(field){
    return $scope.myForm[field].$invalid && $scope.myForm[field].$dirty;
  };

  $scope.isValid = function(field){
    return $scope.myForm[field].$valid && $scope.myForm[field].$dirty;
  };

}

这篇关于如何简化表单验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆