如何设置角度验证以处理模糊和表单提交?

时间:2015-07-18 02:18:27

标签: javascript angularjs forms validation

角度验证目前通过更新模型更改来工作。尽管在keyup上显示这些验证错误并不是非常友好的UI。

理想的解决方案是在模糊上显示错误消息,同时在表单提交上显示。一旦输入第一次模糊并显示错误消息,则需要在键盘/模型更改时更新输入。

我已经看到以下内容允许模型在模糊时更新,但这不是一个理想的解决方案,因为模型仅针对每种情况更新模糊。

<input type="text" name="user" ng-model="user" ng-model-options="{ updateOn: 'blur' }" required>

我还遇到了以下解决方案,它可以很好地处理模糊,然后在出现错误后更改为keyup。虽然验证不适用于表单提交。

http://plnkr.co/edit/VSPOYO16ozq2bKaLl3n9?p=preview

2 个答案:

答案 0 :(得分:1)

为此,您可以使用一个角度范围变量来保持提交表单的状态,默认情况下该变量为 false

$scope.submitted = false;

和一个范围函数,用于验证表单提交中的字段。请记住,表单元素的地名属性必须在功能上进行相同的修改和修改。功能方法是使其通用。您也可以通过访问该输入元素的$dirty$error变量直接写入html模板。

$scope.validateInput = function (name, type) {
  var input = $scope.demoform[name];
          return (input.$dirty || $scope.submitted) && input.$error[type];
};

这是将在表单提交时调用的函数。

$scope.submitForm = function () {
            $scope.submitted = true;
            if ($scope.demoform.$valid) {
                console.log('Submitted!!');
            } else {
                console.log('Not valid!!');
                return false;
            }
        };

现在在html模板上你可以这样写。

<form name="demoform" ng-submit="submitForm()" novalidate="">
    <input type="text" name="name" required="" ng-model="name"/>
    <span ng-show="validateInput('name', 'required')" class="text-danger">Name is required</span>
    <button type="submit" class="btn btn-info" >Save</button>
</form>

现在在表单提交上如果字段无效,您可以看到验证消息。

Demo Plunkr of form validation on form submit in angular

答案 1 :(得分:0)

创建一个绑定到模糊事件的指令,您似乎找到了一个可以工作的指令,但我无法在手机上读取Plunkr,并使用它来设置有效性。

现在在控制器的提交功能中,您需要检查表单是否有错误。

if (Object.keys($scope.formName.$error).length > 0) { 
    return false;
}  

是一种简单的方法,也可以将表单设置为$ submit。