Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  141] [ 4]  / answers: 1 / hits: 77652  / 15 Years ago, thu, august 27, 2009, 12:00:00
<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 :)


More From » validation

 Answers
60

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>

[#98813] Monday, August 24, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;