Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Validate Max Method With a Dynamic Value?

I tried the script of http://jqueryvalidation.org/max-method/.. with examples of static values. how to use the max value but dynamic? I tried with this script but it did not work

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      max: "#field1" //from field1 dynamic value???
    //max: 23 //static value
    }
  }
});
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<form id="myform">
    <lable>value1 : </lable>
    <input type="text" class="left" id="field1" name="field1"><br>
    <lable>no greater than value1 : </lable>
    <input type="text" class="left" id="field" name="field">
      <br/>
<input type="submit" value="Validate!">
</form>

how to work?

like image 315
Wisnu Avatar asked Feb 09 '23 22:02

Wisnu


1 Answers

Return the value of the field using a function.

$( "#myform" ).validate({
    rules: {
        field: {
            required: true,
            max: function() {
                return parseInt($('#field1').val());
            }
        }
    }
});

Remember to enclose the value within parseInt or the number could be evaluated as a string.

Working DEMO: http://jsfiddle.net/dq7wf3qj/

like image 198
Sparky Avatar answered Feb 11 '23 16:02

Sparky