Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate less than

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?

like image 743
John Oxley Avatar asked Aug 11 '09 15:08

John Oxley


People also ask

How do you check if JQuery validate is working?

fn , so simply check whether it exists or not; if (typeof jQuery. fn. validationPlugin === "function") { // It's loaded } else { // It's not. }

What is JQuery validate unobtrusive?

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.

What is JQuery validate?

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.

What is JQuery optional?

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.


2 Answers

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.

like image 52
John Oxley Avatar answered Oct 05 '22 12:10

John Oxley


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"
        }
    }
});
like image 38
Moaaid Jamal Avatar answered Oct 05 '22 12:10

Moaaid Jamal