Jquery Validate: How To Ignore Placeholder Text (Produce Error on Default/Blank)

丶灬走出姿态 提交于 2019-12-05 05:53:41

问题


I'd like to make jquery validate ignore the default text.
The way I have it check for default text is to check if the element.value == the elements alt text

Here's my code, but it returns invalid no matter if its blank, default text, or any other text:

$.validator.addMethod("notDefaultText", function(value) 
{
    if($(this).val()==$(this).attr('alt'))
              return false;

});

        rules: {
        Name: "required notDefaultText",
        Email: "required notDefaultText email"
    },

回答1:


I had the same problem and solved it this way...

The way I have it check for default text is to check if the value == the elements placeholder attr.

$.validator.addMethod("notDefaultText", function (value, element) {
   if (value == $(element).attr('placeholder')) {
      return false;
   } else {
       return true;
     }
});

$("yourForm").validate({
        rules: {
            title: { required: true,
                notDefaultText: true
            },
            description: {
                required: true,
                notDefaultText: true,
                minlength: 2,
                maxlength: 400
            }
        },
        messages: {
            title: "Error text",
            description: {
                required: "Error text",
                notDefaultText: "Error textp",
                minlength: "Error text",
                maxlength: "Error text"
            }
        }

    });



回答2:


HTML5 has support for placeholders as part of markup. You can use jQuery to handle other browsers.

A well presented way to do this is presented at http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html




回答3:


You are probably using the alt on a element that does not take that attribute alt is for images and etc not input fields! Therefore the browser will not accept it.

Try an attribute like: "data-default" or anything with 'data-*' to store these values.

sometimes I find some browsers to read/manipulate certain attributes acting with unexpected behavior.



来源:https://stackoverflow.com/questions/4904017/jquery-validate-how-to-ignore-placeholder-text-produce-error-on-default-blank

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