Reputation: 1280
I am trying to create form builder application in Angular.js and I got stuck on validating fields. Angular provides great validation but one thing is missing for my usecase, and that is turning various validation on / off dynamically. I want to let my user add new form fields and then specify a validation (Angular default minlength, maxlength, ...) for each field alone.
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?
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
validationApp.controller('mainController', function($scope) {
$scope.toggleValidation = function()
{
// ???
}
});
Upvotes: 0
Views: 422
Reputation: 2020
You should consider using something like http://formly-js.github.io/angular-formly/#!/ to dynamically generate forms from a set of JSON objects. Then it would very very easy to toggle certain validation methods on and off.
Upvotes: 3
Reputation: 17721
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...
Upvotes: 0