How to validate input using javascript
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>
If you do not plan on using jQuery this should work.
function validate() {
for (var field in document.getElementsByTagName('input')) {
if (isPriceField(field)) {
field.value = field.value.trim();
if (isNaN(parseFloat(field.value))) {
return alertAndFocus(field, "Please enter a valid price");
}
}
}
return true;
}
function isPriceField(field) {
return (field.name.substr(0, Math.min(5, field.name.length)) === 'price')
}
function alertAndFocus(field, message) {
alert(message);
field.focus();
return false;
}
$('#form input').each(function(){
console.log('valid',$(this)[0].validity.valid);
});