Jquery Validate Incompatible with Placeholder Poly

2019-04-02 01:23发布

问题:

I'm currently using the Placeholder Polyfill by Mathias Bynens in combination with the jquery.validate plugin (v1.11.1) and am running into a frustrating error with Internet Explorer 9.

I cannot get required field validation to work on my type="password" fields if they have a non-empty placeholder attribute defined. Once a value is input and the placeholder text disappears, the remaining validation works fine.

Live Demo of this code can be found here

JS

$('input').placeholder(); // init placeholder plugin
signupFormValidator = $('form').validate(); // init validation

HTML

<form>
  <input class="required" type="text" name="test" id="test" placeholder="test"><br>
  <input class="required" type="password" name="password" id="password" placeholder="password"><br>
  <input class="required" type="password" name="confirm"  id="confirm"  placeholder="confirm"><br>
  <input type="submit">
</form>

回答1:

edit: this fix introduces bugs in Firefox. Please see comment below.


To deal with this, I ended up using some fairly hacky jQuery I baked myself:

$('#password, #confirm').keyup(function() {
    var $input = $(this);
    if ($input.attr('type') === 'text') {
        if ($input.val().length > 0) {
            $input.attr('type', 'password');
        }
    } else if ($input.val() === "") {
        $input.attr('type', 'text');
    }
});

What this is doing, is setting the field type to "text" rather than "password", effectively clearing up that pesky placeholder issue.

Minor issue: the first character of the password displays as plain-text briefly when starting to enter text into the input.