PHP form validation - question
Posted: Thu Mar 27, 2008 7:07 am
Hi,
I am trying to acheive the followings, if you have any better idea I would like to hear from you. Basically, is there a way I can do this without having to print the form twice when there is an error? I would like to highlight areas so that users know where they are making mistakes. (i.e using red border around text field or just simply changing the colour of the labels. etc)
I am trying to acheive the followings, if you have any better idea I would like to hear from you. Basically, is there a way I can do this without having to print the form twice when there is an error? I would like to highlight areas so that users know where they are making mistakes. (i.e using red border around text field or just simply changing the colour of the labels. etc)
Code: Select all
<?
if(form is submitted){
$error='';
$error_name = '';
$error_age = '';
if(field1 is empty or field2 is empty){
$error.='fill in all required fileds';
}
// all fields have been filled with some data
else{
//check if field 1 holds the correct type i.e name and not digit
if(name holds anything other than character){
$error_name.= 'type only character pls';
}
//check if field 2 holds the correct type i.e number and not character
if(age holds anything other than number){
$error_age.= 'type only a number pls';
}
}
//display form
}else{
?>
--- form starts ----
name (formfield1)
age (form field 2)
submit
--- form ends ----
<?
} // end if
if($error is not empty){
print $error
print entire form again
}
// point to the users where they have made mistakes (hightlight form fields etc)
else if($error_name is not empty || $error_age is not empty ) {
print <form name action method>
if($error_name is empty){
print name (formfield1) // normal way
}
else{
print name (formfield1) // heightlight it using css , red coloured border etc
print error_name;
}
repeat the above steps for all other form fields
print </form>
}
?>