PDA

View Full Version : Validate only form fields which is NOT empty


freddd
07-15-2005, 07:20 AM
I have a page that uses a form to build SQL statements. The page consits of several text boxes.
textbox1
textbox2
textbox3
textbox4

What I want to do is to validate only the textboxes where the user has entered some information. If I for instance want to validate textbox2 for numbers and max length 12 I only want to do this IF the user has entered something in textbox2. If the users DON'T enter any data in the textbox2 nothing should occur.

Same goes for all other textboxes IF data is entered a validation should occur, IF NOT don't do anything. I know how to validate for example numbers and length, but again not how to do this only when the field has som input.

Some sample code i'm using:

<script language="JavaScript">
function checkInput(){

if (document.form2.textbox1.value.length < 4){
alert("4");
return (false);
}
if (document.form2.textbox2.value.length < 4){
alert("4");
return (false);
}
if (document.form2.textbox3.value.length < 6){
alert("6");
return (false);
}
if (document.form2.textbox4.value.length < 6){
alert("6");
return (false);
}


}
</script>

How can I modify this code to do what I need?
Thanks in advance...

Mongus
07-15-2005, 07:53 AM
Try something like this (untested)

<script language="JavaScript">
function checkInput(){

var value;

if ((value = document.form2.textbox1.value) != "" && value.length < 4){
alert("4");
return (false);
}
if ((value = document.form2.textbox2.value) != "" && value.length < 4){
alert("4");
return (false);
}
if ((value = document.form2.textbox3.value) != "" && value.length < 6){
alert("6");
return (false);
}
if ((value = document.form2.textbox4.value) != "" && value.length < 6){
alert("6");
return (false);
}


}
</script>


Yes, the assignment in the if statement is intentional. :)

freddd
07-15-2005, 09:04 AM
Thanks a lot it works great!!