tarekahf tarekahf - 3 years ago 234
AngularJS Question

Enable/disable validation for angular sub-form `ng-form`

I need to enable/disable all validation rules in Angular form or subform under

based on a scope variable
. So, if
, none of the validations set for the designated group of fields will run, and the result will always be
, otherwise, the validation rules will run as usual.

I did a lot of research, and realized that this feature is not available out of the box with Angular. However, I found some add-ons or with some customization, it is possible.

For example, I can use the add-on angular-conditional-validation (github and demo) with custom directive
. This will be perfect, except that I cannot apply this feature for a group of fields under
. I have to add this directive for each and every field where applicable.

The other solution is to use custom validation using Angular
pipeline. This requires some extra effort and I don't have time since the sprint is almost over and I have to give some results in a few days.

If you have any other suggestions please post an answer.

Use Case:

To clarify the need for this, I will mention the use-case. The end user can fill the form with invalid data and he can click
button and in this case, the validation rules shouldn't be triggered. Only when the user clicks
Validate and Save
then the validation rules should be fired.


See the final plunker code here. Also see answer below and comments.

Answer Source

One idea is to reset the errors in the digest loop if the validation flag is disabled. You can iterate through the form errors on change and set them to valid, one by one.

$scope.$watch(function() {
}, true);

$scope.changeValidity = function() {
    if ($scope.isValidationRequired === "false") {
        for (var error in $scope.form.$error) {
            while ($scope.form.$error[error]) {
                $scope.form.$error[error][0].$setValidity(error, true);

Here is a plunkr: https://plnkr.co/edit/fH4vGVPa1MwljPFknYHZ

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download