Posted By

ontic on 11/28/10


Tagged


Versions (?)

Range Validation Method Using Class Name


 / Published in: JavaScript
 

Is their a better solution?

  1. <script type="text/javascript">
  2. jQuery(document).ready(function($)
  3. {
  4. $.validator.addMethod("validate-digits-range", function(value, element)
  5. {
  6. var result = this.optional(element) || /^\d+$/.test(value);
  7.  
  8. $.each($(element).attr("class").split(" "), function(index, class)
  9. {
  10. if (result && /^digits-range-[0-9]+-[0-9]+$/.test(class))
  11. {
  12. var min = parseInt(class.split('-')[2], 10);
  13. var max = parseInt(class.split('-')[3], 10);
  14. result = (value >= min) && (value <= max);
  15.  
  16. if (!result)
  17. {
  18. $.validator.messages["validate-digits-range"] = $.validator.format("Please enter a value between {0} and {1}", min, max);
  19. }
  20.  
  21. return false;
  22. }
  23. }
  24. );
  25.  
  26. return result;
  27. },
  28. $.validator.format("Please enter a value between {0} and {1}")
  29. );
  30.  
  31. $("#form-validate").validate();
  32. }
  33. );
  34. </script>

Report this snippet  

You need to login to post a comment.