The jQuery Validation `valid()` method returns 0 when required is not true
19,255
Check this, from the documentation:
Makes "field" required and digits only.
You could do something like this:
var isValid = jQuery('#kiloMetresTravelled').valid() || jQuery('#kiloMetresTravelled').val() == "";
Author by
Glenn Slaven
I'm Principal Engineer at http://www.section.io Been coding for about 20 years now. I'm married & have 4 great kids
Updated on June 05, 2022Comments
-
Glenn Slaven almost 2 years
I'm using the jQuery Validation plugin and I've got a textbox with the class
digits
to force it to be digits only, but not required. When I call validate on the form it works fine, but if I callvalid()
on the textbox when it's empty, it returns 0, despite no error message showing and required not being set.Does anyone know why it would be returning this for a seemingly valid input value?
Here is the code:
<input type="text" value="" name="kiloMetresTravelled" id="kiloMetresTravelled" class="digits"/>
and the script
<script type="text/javascript'> var isvalid = jQuery('#kiloMetresTravelled').valid(); //isvalid == 0 when kiloMetresTravelled is blank </script>
-
Glenn Slaven over 15 yearsDoesn't it only say 'makes the element require digits only'. They added a 'required' rule as well
-
JT. over 12 yearsThe example adds the required rule into the mix: this answer is misleading. What actually happens is that since there is no required rule on the field, the internal 'check' method returns undefined for the field in question. Why this is so is a mystery to me. Note that the code above works but (a) the reason is wrong, and (b) it will only work for a single element under test.