Search code examples
jqueryjquery-validaterequiredonfocuslost-focus

jQuery Validation plugin: add validation rules but need to hide message on focus


The following method is called to make controls mandatory based on some conditions

addRequired = function ($ele, msg, min, minMsg) {
    $ele.rules('add', {
        required: true,
        min: min,
        messages: {
            required: msg,
            min: minMsg
        }
    });

    $.validator.unobtrusive.parseElement($ele.get(0));
}

And the calling code

if (requiredOptions["CompanyName"]) {
    addRequired($('#CompanyName'), 'Company is required');
}
if (requiredOptions["SiteName"]) {
    addRequired($('#SiteNameDD'), 'Enter a Site');
}

The validation is working perfectly. But the requirement is when controls (e.g. CompanyName) are focused, the required message should disappear. Basically, whenever the required control focused, the error message appears. The requirement is to show the message on focusout or form submit events. How could i achieve that?

Updated

From the solution mentioned by @Praveen_Kumar I came up with the following changes

addRequired = function ($ele, msg, min, minMsg) {
        $ele.rules('add', {
           ... ... ...
        });

        // Remove the validator message on focus.
        $ele.on("focus", function () {
            var thisRule = $.validator.staticRules($ele.get(0));
            thisRule.required = false;            
         });

        // Add the validator message on blur.
        $ele.on("blur", function () {
            var thisRule = $.validator.staticRules($ele.get(0));
            thisRule.required = true;
        });
       ...    
}

Solution

  • Just add a bit of code here:

    addRequired = function ($ele, msg, min, minMsg) {
        $ele.rules('add', {
            required: true,
            min: min,
            messages: {
                required: msg,
                min: minMsg
            }
        });
    
        // Remove the validator message on focus.
        $ele.one("focus", function () {
            $.validator.hideMessage($ele.get(0)); // Replace this with the right method.
            $ele.off("focus");
        });
    
        $.validator.unobtrusive.parseElement($ele.get(0));
    }
    

    Here $.validator.hideMessage($ele.get(0)); is a pseudo function, that takes in the element that was parsed and deemed invalid. You have not provided the validator plugin URL to correctly guide you what the exact hide function is.