I am trying to write a Less than
validator for jQuery.
I want to compare one text box against another, so if I have:
<input type="text" id="value1" /> <input type="text" id="value2" />
I want my validator
to look like
$('#myForm').validate({rules: { value1: { lessThan: "#value2" } } });
I have tried this but I can't get it to work:
$.validator.addMethod('lessThan', function(value, element, param) {
var i = parseInt(value);
var j = parseInt($(param).val());
return i >= j;
}, "Less Than");
Another question is where should I put that code? In $(document).ready
or just in a <script>
tag?
fn , so simply check whether it exists or not; if (typeof jQuery. fn. validationPlugin === "function") { // It's loaded } else { // It's not. }
Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js.
Validation in JQuery: Using JQuery, a form is validated on the client-side before it is submitted to the server, hence saves the time and reduce the load on the server. Form Validation means to validate or check whether all the values are filled correctly or not.
optional(element) is to immediately return true if the element is blank AND it is not required. So if you had these two methods: jQuery. validator. addMethod("BOB", function (value, element) { return this.
I'm an idiot. I had made some typo's in my actual code and I'd messed up the this.optional(element) that I see in a lot of validator methods. Here is the working function:
$.validator.addMethod('lessThanEqual', function(value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "The value {0} must be less than {1}");
Here is the condensed version
$.validator.addMethod('lessThanEqual', function(value, element, param) {
return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, "The value {0} must be less than {1}");
Now I need to figure out how to rerun validation for field 1 when I change field2.
Consider (A) is the name of the input that you want the value of it to be less than (#B) input.
this code worked with me after making the type of the two inputs is: type="number"
$("#form").validate({
rules: {
A: {
lessThan: "#B"
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With