如何使用javascript验证输入

wow*_*wow 5 javascript validation

<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" />
Run Code Online (Sandbox Code Playgroud)

这个JavaScript代码工作正常,以验证字段"价格".

题 :

如何使代码作为全局验证工作?示例:将使用单个函数验证价格,price2,price3,price4,price5等.请告诉我 :)

Bri*_*sbe 13

我的个人推荐是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

  • return validatePrice(document.form.price) &amp;&amp; validatePrice(document.form.price2) &amp;&amp; validatePrice(document.form.price3) &amp;&amp; validatePrice(document.form.price4) &amp;&amp; validatePrice(document.form.price5); (3认同)
  • 如何使用数组而不是大的if语句? (2认同)