0

the jsbin

the problem:

<input id="cname" name="name" minlength="2" type="text" required value="test">

comes with given value test. Now when removing the value, the validation plugin does not get triggered.

html

<!DOCTYPE html>
<html>
<head>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>


  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Name comes with value, when value removed, no error shows!</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required value="test">
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" value="" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>

    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form> 
</body>
</html>

JS

$(function(){
  $("#commentForm").validate();  
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
Toskan
  • 13,911
  • 14
  • 95
  • 185

1 Answers1

1

As per documentation, by default, validation is "Lazy".

Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value

This means that simply loading a form and deleting a value will do nothing. You would have to wipe out the value and click the submit button to trigger validation. Then all subsequent interactions are validated on the keyup and focusout events.

DEMO: http://jsfiddle.net/yo4y9s64/


Refer to this answer to implement "Eager" validation...

onkeyup: function (element, event) {
    if (event.which === 9 && this.elementValue(element) === "") {
        return;
    } else {
        this.element(element);
    }
}

DEMO 2: http://jsfiddle.net/yo4y9s64/1/

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • hm ok. But you know, that doesn't make sense. He gets a valid form, makes it invalid manually by pressing buttons on the keyboard, but gets no feedback. So I have to write a listener for keyup myself that triggers a valid on the form ? that's silly – Toskan Jan 06 '16 at 23:07
  • @Toskan, I did not say that. I simply explained how it works by default and quoted the documentation to that effect. If you want "Eager" validation, it's a simple modification that's been answered before: http://stackoverflow.com/a/15104059/594235 – Sparky Jan 06 '16 at 23:14