placeholder issue with jQuery Validate

前端 未结 9 624
时光说笑
时光说笑 2020-12-31 19:10

I noticed today that we have an issue with jquery Validate when used in conjunction with placeholder text.

Example:

&
相关标签:
9条回答
  • 2020-12-31 20:02

    I was coming across the same issue. After some messing around, found a workaround with this custom method. This custom method will accommodate placeholders.

    jQuery.validator.addMethod("placeholder", function(value, element) {
      return value!=$(element).attr("placeholder");
    }, jQuery.validator.messages.required);
    

    Tag this line at the end of the additional-methods.js file.

    You'll then use it as follows:

    $("form").validate({
      rules: {
        username: {required: true, placeholder: true},
      },
      message: {
        username: {
          required: "Username required", placeholder: "Username required",
        },
      }
    });
    
    0 讨论(0)
  • 2020-12-31 20:02

    This is generic way of validating placeholders (use following code AFTER validation logic initialization). It works by injecting custom logic into all validation methods.

    $(function () {
        $.each($.validator.methods, function (key, value) {
            $.validator.methods[key] = function () {
                var el = $(arguments[1]);
                if (el.is('[placeholder]') && arguments[0] == el.attr('placeholder'))
                    arguments[0] = '';
    
                return value.apply(this, arguments);
            };
        });
    });
    
    0 讨论(0)
  • 2020-12-31 20:04

    You could script around it perhaps.

    This will remove placeholder attribute on submit, and restore them in the event of an error.

    var placeholders = {};
    $('form').validate({
       submitHandler: function(form) {
    
           $(form).find(':input[placeholder]').each(function() {
              var placeholder = $(this).attr('placeholder'); 
              placeholders[placeholder] = this;
              $(this).removeAttr('placeholder');
           });       
    
           form.submit();
       },
    
       invalidHandler: function() {
    
          $.each(placeholders, function(placeholder, element) {
              $(element).attr('placeholder', placeholder);
          });
    
       }
    
    });
    
    0 讨论(0)
提交回复
热议问题