Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate that the max field is greater than the min field?

I have a few sets of min and max fields in a form, where the user can specify a range by filling in a min and a max. I'm using jQuery's Validate plugin for my form validation. I'd like to set up a validation rule that enforces that the max field is greater than the min. This would be invoked whenever the max or the min fields values are changed.

I know I can set up some sort of basic custom validation method like this:

$.validator.addMethod("greaterThan",
    function(value, max, min){
        return parseInt(value) > parseInt($(min).val());
    }, "Max must be greater than min"
);

And then add a rule for the max element:

rules: {
    maxTruck: {greaterThan: '#minTruck'}
}

But it's a bit more complicated because this only applies when the max field is changed, not the min. Is there any simple way to do this without having to write a lessThan method and apply that to the min field?

And then another thing I'd like to tackle - is there any simple way that I can apply this generically instead of having to enumerate each max field and which min it maps to? So that I can just have a min and max class and call something like:

$(".max").rules('add', { greaterThan: ".min" });

And somehow set up the method to be able to figure out (maybe based on a shared attribute?) which min the max field is paired with?

Update:

The basic logic that I mentioned in this post can be seen in this jsfiddle. However, I have not really worked on this much - I am looking for the logic to basically link sets of min and max fields the way I described. And I don't know if this is the best way to do this - as I mentioned, I'd love to be able to do this generically so that I don't have to refer to the min and max fields by id.

like image 715
froadie Avatar asked Jan 15 '13 21:01

froadie


People also ask

How do you validate min max?

We can validate Min Max values on typing by using onCreate event of NumericTextbox and normal keydown event. In keydown we have used a Timeout function where we can specify the time in milliseconds after which the validation automatically takes place inside the NumericTextbox.

What are the validation rules in property of field?

Field validation rules Use a field validation rule to check the value that you enter in a field when you leave the field. For example, suppose you have a Date field, and you enter >=#01/01/2010# in the Validation Rule property of that field. Your rule now requires users to enter dates on or after January 1, 2010.

What do you mean by validation rule?

Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”.


2 Answers

Simple and good way to use addmethod

$.validator.addMethod("greaterThan",

function (value, element, param) {
  var $min = $(param);
  if (this.settings.onfocusout) {
    $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
      $(element).valid();
    });
  }
  return parseInt(value) > parseInt($min.val());
}, "Must be greater than to field 1");

validating code

filed2_name: {

            greaterThan: '#filed1_id'
        },  

second i prefer first

$.validator.addMethod('le', function(value, element, param) {
      return this.optional(element) || value <= $(param).val();
}, 'Invalid value');
$.validator.addMethod('ge', function(value, element, param) {
      return this.optional(element) || value >= $(param).val();
}, 'Invalid value');

$('form').validate({rules: {
            fieldName1: {le: '#fieldID2'},
            fieldName2: {ge: '#fieldID1'},
             ...
      },
      messages: {
            fieldName1: {le: 'Must be less than or equal to field 2'},
            fieldName2: {ge: 'Must be greater than or equal to field 1'},
            ...
      }
});
like image 124
user2964333 Avatar answered Sep 24 '22 00:09

user2964333


Ok, here's something that should work. The rule is based on the built in equalTo method:

$.validator.addMethod("greaterThan", function (value, element, param) {
    var $min = $(param);

    if (this.settings.onfocusout) {
        $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
            $(element).valid();
        });
    }

    return parseInt(value) > parseInt($min.val());
}, "Max must be greater than min");

Example: http://jsfiddle.net/tUPQc/2/


To make the rule a bit more generic, you'll have to need to use addClassRules:

$.validator.addMethod("greaterThan", function (value, element, param) {
    var $element = $(element)
        , $min;

    if (typeof(param) === "string") {
        $min = $(param);
    } else {
        $min = $("#" + $element.data("min"));
    }

    if (this.settings.onfocusout) {
        $min.off(".validate-greaterThan").on("blur.validate-greaterThan", function () {
            $element.valid();
        });
    }
    return parseInt(value) > parseInt($min.val());
}, "Max must be greater than min");

$.validator.addClassRules({
    greaterThan: {
        greaterThan: true
    }
});

Then in your HTML:

<input id="maxTruck" name="maxTruck" type="text" class="number greaterThan" data-min="minTruck" />

Example: http://jsfiddle.net/tUPQc/3/

like image 21
Andrew Whitaker Avatar answered Sep 24 '22 00:09

Andrew Whitaker