jquery validate - validating a field on pageload

自闭症网瘾萝莉.ら 提交于 2020-02-26 03:42:25

问题


I've got an input field on my plain html form that I would like to be marked as invalid (and the error message shown) from the moment the page loads.

Is this possible to do with the jquery validate plugin?

Failing that, how can I hide an element when the plugin tries to validate a particular input field?


回答1:


I think you would have to have the form you are validating be submit on the page load. Probably something like this:

   $(document).ready(function() {
       $('form').validate(/* set all of your validator options here */);
       $('form').trigger('submit');
    });



回答2:


Managed to come up with a solution. It involved adding a 'dummy' validation element that is shown when the page is loaded. As soon as the user inputs a value into the corresponding field, the dummy element is hidden and the real one is shown.

I used the highlight and unhighlight options for the validate method to achieve what i wanted.

$("#myform").validate({
    highlight: function(element){
        if($(element).hasClass("math")){
           $(".temp").hide();
        }
    },

    unhighlight: function(element){
        if($(element).hasClass("math")){
           $(".temp").hide();
        }
    }
});

Maybe this will help someone else out in future.



来源:https://stackoverflow.com/questions/2464281/jquery-validate-validating-a-field-on-pageload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!