[英]Add angular field validation dynamically
I am trying to create form builder application in Angular.js and I got stuck on validating fields. 我试图在Angular.js中创建表单生成器应用程序,但在验证字段时遇到问题。 Angular provides great validation but one thing is missing for my usecase, and that is turning various validation on / off dynamically.
Angular提供了很好的验证,但我的用例却缺少一件事,那就是动态地打开/关闭各种验证。 I want to let my user add new form fields and then specify a validation (Angular default minlength, maxlength, ...) for each field alone.
我想让我的用户添加新的表单字段,然后为每个字段单独指定一个验证(Angular默认的minlength,maxlength等)。
Lets say that I want to create a button, that will add / remove minlength validation on a specified field (fields are stored in my model and are displayed through custom form and field directives), how should I do this? 假设我要创建一个按钮,该按钮将在指定字段上添加/删除最小长度验证(字段存储在我的模型中,并通过自定义表单和字段指令显示),我该怎么做?
I created a simple Plunker - http://plnkr.co/edit/pCXgwgnNbZkcAcl263JN?p=preview can you tell me what shoud be inside the toggleValidation()
function? 我创建了一个简单的Plunker- http: //plnkr.co/edit/pCXgwgnNbZkcAcl263JN?p=preview您能告诉我
toggleValidation()
函数中应该包含什么吗?
HTML 的HTML
<div ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }" class="form-group">
<label>Name</label>
<input type="text" ng-model="user.name" class="form-control" name="name" />
<p class="help-block" ng-show="userForm.name.$invalid && !userForm.name.$pristine">Validation error.</p>
</div>
<a href="" class="btn btn-success" ng-click="toggleValidation()">Toggle minlength validation</a>
JS JS
validationApp.controller('mainController', function($scope) {
$scope.toggleValidation = function()
{
// ???
}
});
You should consider using something like http://formly-js.github.io/angular-formly/#!/ to dynamically generate forms from a set of JSON objects. 您应该考虑使用http://formly-js.github.io/angular-formly/#!/之类的东西来从一组JSON对象动态生成表单。 Then it would very very easy to toggle certain validation methods on and off.
然后,非常容易地打开和关闭某些验证方法。
I should try something like this: 我应该尝试这样的事情:
validationApp.controller('mainController', function($scope) {
$scope.toggleValidation = function(validationFlag) {
$scope.validationIsOn = validationFlag;
}
$scope.minlengthValidation = function (field, minlen) {
if ($scope.validationIsOn) {
return (field.length >= minlen);
} else {
return true;
}
}
});
Note: this code is not real code, but it just wants to give an idea to build the real code... 注意:此代码不是真实的代码,但是它只是想给一个构想真实的代码...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.