使用jQuery(form)验证插件的简单数学验证JavaScript脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用jQuery(form)验证插件的简单数学验证JavaScript脚本相关的知识,希望对你有一定的参考价值。

Don't forget to include jQuery validation plugin before this snippet. You can find it here:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/
  1. jQuery(document).ready(function() {
  2. var send_email_form = jQuery("form#my-form");
  3. var lowerBound = 1;
  4. var upperBound = 10;
  5. // to generate random numbers between a range that starts somewhere other than
  6. // zero use this formula where m is the lowest possible integer value of the range
  7. // and n equals the top number of the range.
  8. // Math.floor(Math.random() * (n - m + 1)) + m
  9.  
  10. // generate random numbers between lowerBound and upperBound (inclusive)
  11. var a = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
  12. var b = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
  13.  
  14. jQuery("label#arithmetic_expression").html(a + " + " + b + " = ");
  15. jQuery("input#eqtn_soln").val(a+b);
  16.  
  17. var validation_rules = {
  18. name: "required",
  19. email: {
  20. required: true,
  21. email: true
  22. },
  23. subject: "required",
  24. message: "required",
  25. sum: {
  26. required: true,
  27. equalTo: "input#eqtn_soln"
  28. }
  29. };
  30.  
  31. var validation_messages = {
  32. name: "please enter your name",
  33. email: {
  34. required: "Please enter your email address",
  35. email: "Please enter a valid email address"
  36. },
  37. subject: "please enter a message subject",
  38. message: "please enter the message",
  39. sum: {
  40. required: "please answer the equation",
  41. equalTo: "please answer the equation correctly"
  42. }
  43. };
  44.  
  45. //form validation with javascript
  46.  
  47. send_email_form.validate({
  48. rules: validation_rules,
  49. messages: validation_messages,
  50. //errorClass: "form-error-style",
  51. errorPlacement: function(error, element){
  52. // places the error message after the element one line break below
  53. error.insertAfter(jQuery("<br />").insertAfter(element));
  54. }
  55. });
  56. });

以上是关于使用jQuery(form)验证插件的简单数学验证JavaScript脚本的主要内容,如果未能解决你的问题,请参考以下文章

一个简单的jQuery插件,用于验证表单。

JQUERY.form插件简单使用

jQuery 验证插件未在 form$.validate() 上进行验证

与 <from:form> 标签一起使用时,Jquery 验证插件不显示消息?

jquery验证插件

jquery插件-表单验证插件-validator对象