Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

placeholder issue with jQuery Validate

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

Example:

<div class="sort left">
<label for="username" class="inlineelement">Username</label>
<input id="registername"  type="text" placeholder="your name" autocomplete="off" class="required"></input>

I noticed that , if we validate our form using jquery Validate ( http://docs.jquery.com/Plugins/Validation/Methods )

Is there a work around for this, or should be go back to focus html ( placeholder text ) within our form fields ?

like image 813
422 Avatar asked May 20 '11 01:05

422


2 Answers

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",
    },
  }
});
like image 102
jonsuh Avatar answered Oct 11 '22 23:10

jonsuh


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);
        };
    });
});
like image 20
Hogan Avatar answered Oct 11 '22 23:10

Hogan