2

I have my form validations dynamically added to the form from a response to a web service call. When the call returns it tells my validation directive what validations I need to add to the form. (I do this because I want to reuse the same validations on the server during submit as I do on the client.) This works wonderfully when the only validations are of type "required". The problem I have is when the model value of the form control does not pass the the validation rules, the model value is then "undefined". Therefore nothing get's sent to the server on form submission to validate on the server side. I do realize I could block the form submission if the form is not valid, however, I am letting the server determine the validity of the data that comes across.

What could I do to force the model value to be the "invalid value" regardless if it violated a validation rule? Better suggestions? Below is a snipit of my directive I am using.

    //this directive should be put on an ng-form element and it will hide/show any validations set on each input
    .directive('formValidator', ['validatorService', function (vs) {
        return {
            restrict: 'A',
            require: '^form',
            link: function (scope, element, attrs, form) {

                function iterateOverErrorsObject(errors, func, ignorechecking) {
                    if (!func)
                        return;

                    //show any new errors
                    for (var key in errors) {
                        if (key.indexOf('__') == 0)
                            continue;

                        _.each(errors[key], function (obj) {
                            if (form[obj.$name] == obj || ignorechecking) { //ensure the obj is for the current form
                                var input = vs.findElementByName(element, obj.$name);
                                if (input.length > 0) {
                                    func(input, obj);
                                }
                            }
                        });
                    }
                }

                scope.$watch(function () { return form.$error; }, function (newval, oldval, scp) {
                    iterateOverErrorsObject(oldval, function (input, obj) {
                        vs.hideErrors(input);
                    }, true);
                    iterateOverErrorsObject(newval, function (input, obj) {
                        vs.showErrors(input, obj, form._attr);
                    });
                }, true);

                //something told the validator to show it's errors
                scope.$on('show-errors', function (evt) {
                    iterateOverErrorsObject(form.$error, function (input, obj) {
                        vs.showErrors(input, obj, form._attr);
                    });
                });

                scope.$on('hide-errors', function (evt) {
                    vs.hideAllErrors(form);
                });
            }
        };
    }])
    //this directive is to be put on the ng-form element and will dynamically add/remove validators based on the validations configuration
    //which comes back from the service call "Validate"
    .directive('dynamicValidators', ['$compile', function ($compile) {
        return {
            priority: 0,
            restrict: 'A',
            //require: 'ngModel',
            require: '^form',
            scope: {
                'validations': '=',
            },
            link: function (scope, element, attrs, ctrl) {
                (function (form, scp) {

                    // this will hold any information necessary to get the error message displayed
                    // **have to add the form because the ctrl gets recreated every time the form.$error changes
                    function setAttr(ctrl, key, value) {
                        if (!ctrl._attr)
                            ctrl._attr = {};
                        if (!form._attr)
                            from._attr = {};

                        ctrl._attr[key] = value;
                        var obj = form._attr[ctrl.$name] = {};
                        obj[key] = value;
                    };

                    scope.$watch('validations', function (nv, ov) {
                        form._attr = {};
                        //remove old validators
                        if (ov && ov.length > 0) {
                            _.each(ov, function (e) {
                                var fctrl = form[e.MemberNames[0]];
                                if (fctrl && fctrl.$validators) {
                                    delete fctrl.$validators[e.ErrorKey];
                                    //fctrl.$setValidity(e.ErrorKey, true);
                                    fctrl.$validate();
                                }
                            });
                        }

                        //add new validators
                        if (nv && nv.length > 0) {
                            _.each(nv, function (e) {
                                var fctrl = form[e.MemberNames[0]];
                                if (!fctrl)
                                    return;

                                if (e.ErrorKey == 'required') {
                                    setAttr(fctrl, e.ErrorKey, e.ErrorValue);
                                    fctrl.$validators[e.ErrorKey] = function (modelValue, viewValue) {
                                        if (modelValue instanceof Array)
                                            return modelValue.length > 0;
                                        else
                                            return modelValue !== '' && modelValue !== null && modelValue !== undefined;
                                    };
                                } else if (e.ErrorKey == 'alphanumeric') {
                                    setAttr(fctrl, e.ErrorKey, e.ErrorValue);
                                    fctrl.$validators[e.ErrorKey] = function (modelValue, viewValue) {
                                        return viewValue == null || (viewValue != null && /^[a-zA-Z0-9]*$/.test(modelValue));
                                    };
                                } else if (e.ErrorKey == 'min') {
                                    setAttr(fctrl, e.ErrorKey, e.ErrorValue);
                                    fctrl.$validators[e.ErrorKey] = function (modelValue, viewValue) {
                                        return modelValue === undefined || modelValue === null || modelValue === "" || modelValue >= e.ErrorValue;
                                    }
                                } else if (e.ErrorKey == 'max') {
                                    setAttr(fctrl, e.ErrorKey, e.ErrorValue);
                                    fctrl.$validators[e.ErrorKey] = function (modelValue, viewValue) {
                                        return modelValue === undefined || modelValue === null || modelValue === "" || modelValue <= e.ErrorValue;
                                    }
                                }

                                //make the validator fire to set the status of the validator
                                if (fctrl.$validators[e.ErrorKey])
                                    //fctrl.$setValidity(e.ErrorKey, fctrl.$validators[e.ErrorKey](fctrl.$modelValue, fctrl.$viewValue))
                                    fctrl.$validate();
                            });
                        }
                    });
                })(ctrl, scope);
            },
        }
    }]);
4
  • I don't know what you mean by "force the model value to be the 'invalid value'" -- but if you're using the same validation rules on both client and server, then sending an invalid form to the server is a waste of the user's time. Just block the submit if client-side validation fails. Feb 8, 2016 at 17:21
  • (And I realize you said you realize you could do that, but are "letting the server determine the validity of the data that comes across" -- but if that were the case why have clientside validation at all?) Feb 8, 2016 at 17:23
  • The example is this. An input must be alphanumeric but is not required. A value of "12-1" in the input, if letters and numbers only validations were set on the input, the model value would be "undefined" (because it has the '-' in it). The $viewValue on the client would still show the value "12-1" although the submit would send an "undefined". There's the problem. Server would say... oh nothing set, so not invalid while the client says "12-1" is invalid and set's the input model to undefined. --yes I could check on the client side but I would have to do the same on the server side.
    – hewstone
    Feb 8, 2016 at 19:47
  • 2
    As far as I can tell the answer to that is "so don't do that." If you're going to do enough clientside validation to change the modelValue, then do it all the way and give the user the opportunity to correct the error before it submits. If you're not going to do that, then don't do clientside validation at all, because it's not doing you or the user any good. Feb 8, 2016 at 20:16

1 Answer 1

16

If you still want to send to the server invalid data, you can use the allowInvalid option with the ngModelOptions directive:

<input type="text" name="userName"
         ng-model="user.name"
         ng-model-options="{ allowInvalid: true }" />

From the documentation for ngModelOptions:

Model updates and validation

The default behaviour in ngModel is that the model value is set to undefined when the validation determines that the value is invalid. By setting the allowInvalid property to true, the model will still be updated even if the value is invalid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.