Jump to content

looping through...


jimfog

Recommended Posts

I want to check that the required form data submitted by a user conform to some standards. That the phone for example is indeed more than 5 digits and that the price entered is indeed a number and not a string. As a first step I have created an array named @required and tried to use a foreach loop to accomplish what I want:

foreach ($required as $value) {			 }  

But I do not know how to proceed from that point.What complicates things is the fact that every fields required different type of check-for which I have constructed corresponding functions. For example...this is the function that validates the phone:

function val_phone($phone){     $phonepr= preg_replace(array('/^\+/', '/\D/','--'), array('', '',''), trim($phone));if((strlen($phonepr) <5) || (strlen($phonepr) > 12)){	 return false;}return true;}

Things would be a lot easier if I was just checking some common attribute-if for example all the fieldswere submitted or not.But here every field must obey different validation rules. What do you think?

Link to comment
Share on other sites

You have to validate each field individually, a loop just can't do that. The page has to be built for the data it's going to receive.
Yes...I agree. I wanted to post though so that I am certain.
Link to comment
Share on other sites

You can structure the array to hold the name of the variable to validate, or the value, and the name of the function to validate it with if you want to use that. You would also probably want to include the error message to show if validation fails.

Link to comment
Share on other sites

Can you give me a small example please, just to get a grasp a little.

Link to comment
Share on other sites

$validate = array(  array('name' => 'variable1', 'validate' => 'function1', 'error' => 'Error message 1'),  array('name' => 'variable2', 'validate' => 'function2', 'error' => 'Error message 2'));

Then you can loop through that array, get the variable name to validate, call the function with the designated name and pass the value to validate, and show the error message if the function returns false.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...