我有以下基本设置来计算/验证面积(平方米m2)。我需要知道的是如何编写JQuery才能做到这一点?我有两个“screen_width”和“screen_height”的输入字段。
条件是:宽度或高度均不得超过3米。总面积m2不得超过4m2。(即1500 mm x 3000 mm = 4.5m2)我不介意3000的独立长度检查,但当面积超过4m2(宽x高)时,我只需要一个错误输出。
$("#area_form").validate({
debug: true,
errorContainer: "#error-output",
errorLabelContainer: "#error-output ul",
wrapper: "li",
rules: {
screen_width: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4
},
screen_height: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4
}
},
messages: {
screen_width: {
required: "Width required.",
digits: "Digits only.",
range: "Exceeding 3000mm.",
maxlength: "Max 4 digits."
},
screen_height: {
required: "Height required.",
digits: "Digits only.",
range: "Exceeding 3000mm.",
maxlength: "Max 4 digits."
}
}
});
<form name="area_form" id="area_form" action="target.php" method="post">
<label for="screen_width">Screen Width</label>
<input type="text" name="screen_width" id="screen_width" maxlength="4" autocomplete="off">
<label for="screen_height">Screen Height</label>
<input type="text" name="screen_height" id="screen_height" maxlength="4" autocomplete="off">
<div id="error-ouput">
<ul>
</ul>
</div>
</form>
我想我可能需要这样的东西,然后是实际的计算:
$.validator.messages.max = jQuery.validator.format("Your area may not exceed {0}!");
但除此之外,我迷失了,我希望尽可能清楚地说明我需要什么。我很感激任何帮助,谢谢你!
答案 0 :(得分:1)
引用OP:
&#34;我想我可能需要这样的东西,然后是实际的计算:&#34;
$.validator.messages.max = jQuery.validator.format("Your area may not exceed {0}!"
在此处使用param
参数,它也会在消息中插入{0}
...
jQuery.validator.addMethod("maxsquare", function(value, element, params) {
return ($('#screen_width').val() * $('#screen_height').val()) <= params[0];
}, jQuery.validator.format("Square area cannot exceed {0}."));
在.validate()
...
rules: {
screen_width: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4,
maxsquare: 4000000 // <-- set the rule & parameter
},
screen_height: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4,
maxsquare: 4000000 // <-- set the rule & parameter
}
},
请参阅文档:http://jqueryvalidation.org/jQuery.validator.addMethod/
您可以更进一步,并将其他字段名称作为另一个参数传递,并按设计使用element
和value
参数。这样,该方法更通用;它并不总是与两个特定的领域联系在一起。
rules: {
screen_width: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4,
maxsquare: ['#screen_height', 4000000] // <-- set the rule & parameters
},
screen_height: {
required: true,
digits: true,
range: [1, 3000],
maxlength: 4,
maxsquare: ['#screen_width', 4000000] // <-- set the rule & parameters
}
},
maxsquare
方法:
jQuery.validator.addMethod("maxsquare", function(value, element, params) {
return (value * $(params[0]).val()) <= params[1];
}, jQuery.validator.format("Square area cannot exceed {1}."));
工作演示:http://jsfiddle.net/scLhR/
旁注:当您已在maxlength="4"
内宣布maxlength: 4
时,您的HTML中不需要属性rules
您.validate()
内的}选项。如果您碰巧更改了其中一个的值,您的结果可能会出乎意料。
答案 1 :(得分:0)
jQuery.validator.addMethod("maxsquare", function(value, element) {
return ($('#screen_width').val() * $('#screen_height').val()) <= 4000000;
}, "Max square...");