本文介绍了如何使用javascript验证输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<script type="text/javascript">
function validate() {
if (document.form.price.value.trim() === "") {
alert("Please enter a price");
document.form.price.focus();
return false;
}
if (document.form.price.value !== "") {
if (! (/^\d*(?:\.\d{0,2})?$/.test(document.form.price.value))) {
alert("Please enter a valid price");
document.form.price.focus();
return false;
}
}
return true;
}
</script>
<form action="" method="post" name="form" id="form" onsubmit="return validate(this);">
<input name="price" type="text" class="r2" />
<input name="price2" type="text" class="r2" />
<input name="price3" type="text" class="r2" />
<input name="price4" type="text" class="r2" />
<input name="price5" type="text" class="r2" />
...more....
<input name="price50" type="text" class="r2" />
此javascript代码可以正常验证字段价格。
This javascript code is working fine to validate the field "price".
问题:
如何使代码作为全局验证工作?示例:将使用单个函数验证价格,price2,price3,price4,price5等。请告知我们:)
How to make the code to work as global validation? Example: would validate the price, price2, price3, price4, price5 etc.. with a single function. Please let me know :)
推荐答案
我的个人推荐是这样的:
My personal recommendation would be something like this:
<script type="text/javascript">
function validate() {
return [
document.form.price,
document.form.price2,
document.form.price3,
document.form.price4,
document.form.price5
].every(validatePrice)
}
function validatePrice(price)
{
if (price.value.trim() === "") {
alert("Please enter a price");
price.focus();
return false;
}
if (price.value !== "") {
if (! (/^\d*(?:\.\d{0,2})?$/.test(price.value))) {
alert("Please enter a valid price");
price.focus();
return false;
}
}
return true;
}
</script>
这篇关于如何使用javascript验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!