<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代碼工作正常,以驗證字段「價格」。如何驗證輸入使用javascript
問:
如何使代碼作爲全球驗證工作?例如:用單一函數驗證價格,price2,price3,price4,price5等。請讓我知道:)
#包括有關始終驗證數據服務器端的一般警告。 – BoltBait 2009-08-27 23:55:56
而不是使用正則表達式來找出它是否是一個數字,可能使用parseFloat?請參閱:http://www.w3schools.com/jsref/jsref_parseFloat.asp – strager 2009-08-27 23:58:15