1

I've been working on getting the jQuery validation plugin to work with Asp.Net webforms in a way that will allow me to mimic the behaviour of validation groups.

The code I have written is based upon Dave Wards blog entry here with some enhancements designed to allow me to customise the rules and messages displayed for each group.

The process is supposed to work as follows:

  1. Default form behaviour is altered.

  2. A method is called which uses Ajax to load up to jSON objects contining the relevent rules/messages for that group.

  3. The defaults for the validation plugin are overwritten.

  4. Each element within the group is tested and if it fails the click event will prevent default submission.

Unfortunately the validation test is returning true on each element within the group. The only thing I can think of just now is that the rules I am setting up are incorrect. I am declaring each rule with it's attribute name based on the name of the element. Is this correct?

e.g.

"ui_txt_Password": { "required": true, "minlength": 5 }

My validation code so far.... Apologies for the sheer quantity, I could maybe post a jsfiddle if required though there are quite a few dependencies on other ajax based methods so it could get messy.

Thanks in advance!

    var validation = {

        selectorExpr: "fieldset.vldgroup",
        validateAndSubmit: function ($validator, event) {
            // Ascend from the button that triggered this click event 
            // until we find a container element flagged with 
            // .vldgroup and store a reference to that element.
            var $group = $(event.currentTarget).closest(validation.selectorExpr),

            // The validation id to fetch the rules/messages for.
                validationId = $group.attr("data-validation-id");

            $.when(i18n.getValidationMessages(validationId), resources.getValidationRules(validationId)).then(function (messages, rules) {

                // Set the default valid status.
                var formIsValid = true,

                // Since jSON doesn't allow functions to be parsed we need to convert any min/max/range data to accept a function.
                    rangeProperties = ["maxlength", "minlength", "rangelength", "range", "max", "min"];

                $.each(rangeProperties, function (key, val) {

                    // Loop through the properties and check.
                    // TODO: Should we support Safari 2.0.1 and below?
                    // http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript
                    if (messages.hasOwnProperty(val)) {

                        // Create a temporary object with a dynamic property name to
                        // extend messages with.
                        var temp = {};
                        temp[val] = $.validator.format(messages[val]);

                        // Extend the messages object.
                        $.extend(messages, temp);

                        // Clean up
                        temp = null;
                    }

                });

                // Set the default rules to match the current form.
                $.validator.setDefaults({
                    messages: messages,
                    rules: rules,
                    errorContainer: $("fieldview[data-validation-id=\"" + validationId + "\"] .vld_summary")
                });

                log($.validator.defaults);

                // Descending from that .vldgroup element, find any input
                // elements within it, iterate over them, and run validation on 
                // each of them.
                $group.find(":input, :checkbox, :password, select").each(function (key, val) {

                    if ($validator.element($(val)) === false) {

                        formIsValid = false;
                    }

                });

                // If any fields failed validation, prevent the button's click 
                // event from triggering form submission.
                if (formIsValid === false) {
                    event.preventDefault();
                }

            });

        },

        init: function () {

            if ($(validation.selectorExpr).length > 0) {

                // Initialize validation on the entire ASP.NET form.
                var $validator = $("form").validate({
                    // This prevents validation from running on every
                    // form submission by default.
                    onsubmit: false
                });

                // Bind the click handlers.
                // Search for controls marked with the .validtrigger flag 
                // that are contained anywhere within elements marked as 
                // validategrp, and wire their click event up.
                $(document).delegate(validation.selectorExpr + " .vldtrigger", "click", function (event) {

                    validation.validateAndSubmit($validator, event);

                    // Select any input[type=text] elements within a validation group
                    //  and attach keydown handlers to all of them.
                }).delegate(validation.selectorExpr + " :text", "keydown", function (event) {

                    // We're only interested in the enter key (13).
                    if (event.which === 13) {

                        // We want to prevent the default form action regardless.
                        event.preventDefault();

                        // Find and store the next input element that comes after the
                        //  one in which the enter key was pressed.
                        var $nextInput = $(this).nextAll(":input:first");

                        // If the next input is a submit button, trigger its click event.
                        // Else, focus the next form element as if enter === tab.
                        if ($nextInput.is(":submit")) {

                            $nextInput.click();

                        }
                        else {

                            $nextInput.focus();

                        }
                    }

                });
            }

        }
    };
James South
  • 10,147
  • 4
  • 59
  • 115

0 Answers0