Issue with chaining Required Field and Regular Expression validators for Textbox controls

后端 未结 4 964
失恋的感觉
失恋的感觉 2021-01-19 10:55

I\'m trying to implement a form validation with ASP.net and I have tried every solution suggested here but the best one was on aspsnippets.com so far.

My code is lik

4条回答
  •  [愿得一人]
    2021-01-19 11:40

    The possible problem is that the code loops through all the validators but does not compare the ones that reference the same control at once. This causes only the last validator condition to be applied on the control.

    Yes, this is indeed the problem. To fix it, you can do the following:

    In the WebForm_OnBlur function, loop through the validators associated with the control that lost focus (rather than all the validators on the page), and clear the className property only if all the validators are valid:

    function WebForm_OnBlur(control) {
        for (var i = 0; i < control.Validators.length; i++) {
            if (!control.Validators[i].isvalid) {
                control.className = "error";
                return;
            }
        }
        control.className = "";
    }
    

    In the onblur attribute of the TextBox controls, pass this as the argument to WebForm_OnBlur:

    
    
    

    In the WebForm_OnSubmit function, call WebForm_OnBlur for each control that has associated validators:

    function WebForm_OnSubmit() {
        if (typeof(ValidatorOnSubmit) === "function" && ValidatorOnSubmit() === false) {
            for (var i = 0; i < Page_Validators.length; i++) {
                var control = document.getElementById(Page_Validators[i].controltovalidate);
                if (Page_Validators[i] === control.Validators[0]) // minor optimization
                    WebForm_OnBlur(control);
            }
            return false;
        }
        return true;
    }
    

提交回复
热议问题