Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

validation - How to validate input using 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" />

This javascript code is working fine to validate the field "price".

Question :

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...