Forum Moderators: open
var field = form.name;
var name = parseInt(field.value);
if (!name) {
alert("Please enter your name.");
return false;
} else if ...... etc etc
i have a bunch of fields on this page that i need to validate and i would like to SKIP the first line...
is it possible for me to do something like this:
var name = parseInt(form.name.value); ?
Thanks a lot guys!
First of all: Welcome to Webmaster World!
As for your question, you can indeed do as you say. In fact you can even go a step further:
if (!parseInt(formname.fieldname.value) ) {
alert("Please enter your name.");
return false;
}
Also, you might want to consider putting the form object names in an array and then cycle through the array instead of a bunch of 'else if' statements.
In fact, if you want to be really slick, you can create an array, each row of which contains an object with a property containing the object name and the text you want to display if the field validation fails:
<head>
<script type="text/javascript">
<!--
//this function creates an object with two properties:
//ObjectID which contains a reference to the form object
//ObjectMessage which contains the message to be displayed if the form object fails validation
function valArray(obj,cMessage){
this.ObjectID = obj
this.ObjectMessage=cMessage
}
//here we initialize the array of fields to validate
var fieldArray = new Array()
//here we fill each element of the array with a valArray object by passing the name of the form object and a validation message to the valArray function
fieldArray[0]=new valArray('txtName','Please enter your name')
fieldArray[1]=new valArray('txtAddress','Please enter your address')
fieldArray[2]=new valArray('txtCity','Please enter your city')
fieldArray[3]=new valArray('txtState','Please enter your state')
fieldArray[4]=new valArray('txtZip','Please enter your ZIP code')
//this function validates the objects
function validateForm(){
//cycle through array of form objects
for(i=0;i<fieldArray.length;i++){
//display alert if length of value is less than one (blank)
if(document.getElementById(fieldArray[i].ObjectID).value.length<1){
alert(fieldArray[i].ObjectMessage)
}
}
}
//-->
</script>
</head>
<body>
<form>
<input type="text" name="txtName" id="txtName" value="" /><br />
<input type="text" name="txtAddress" id="txtAddress" value="" /><br />
<input type="text" name="txtCity" id="txtCity" value="" /><br />
<input type="text" name="txtState" id="txtState" value="" /><br />
<input type="text" name="txtZip" id="txtZip" value="" /><br />
<input type="button" onclick="validateForm()" value="validate" />
</form>
</body>
You could also add rules for various types of input (date, email, etc.)
ajkimoto