I've successfully used the definition on other pages before. Basically it should make the field required, but fail if only whitespace is entered (by default typing ie a single space causes the required check to pass). I tossed an alert in just to see when the handler is fired as well as the value of this
at that time. It's fired when I expect it, and the value is as I expect it. It should be returning false
but apparently it isn't because the error isn't being displayed. If I remove that depends
function and just have required: true
, it correctly displays the error when the user leaves the field. What's going on?
ContactName: {
required: {
depends: function() {
alert("'" + $(this).val() + "'");
if ($.trim($(this).val()).length === 0) {
$(this).val($.trim($(this).val()));
return false;
}
return true;
}
},
maxlength: 100
}
You can change the rule for ContactName like (for details take a look to rules examples ):
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
The snippet:
$("#commentForm").validate({ rules: { ContactName: { required: true, minlength: { depends: function(ele) { if (ele.value.trim().length === 0) { ele.value = ''; return false; } return true; } }, maxlength: 100 } }, messages: { ContactName: "Please enter your contact name" } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <p> <label for="ContactName">Name</label> <input id="ContactName" name="ContactName" type="text"> </p> <p> <input class="submit" type="submit" value="Submit"> </p> </fieldset> </form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.