ravravrav Posted November 25, 2006 Share Posted November 25, 2006 HiI have a very basic registration form which currently adds the data to my Users table with no validation.Can I add validation so that if anything is wrong the validation text will display at the top of the form?eg.'Please fill in your password'would display at the top of the form etc. ??? Link to comment https://forums.phpfreaks.com/topic/28385-registration-validation/ Share on other sites More sharing options...
bahewitt Posted January 2, 2009 Share Posted January 2, 2009 Hi Rav It is pretty easy using an if statement. For instance lets say the variables are: $username $password $email. You can have your script as follows: If ($username == "") { echo "not filled in"; } Do this for each variabale. With this construct all errors will be shown. I personally don't want the whole page full of errors as I have about thirty I check for so I use what i call a rolling error checker by using the exit command as follows: If ($username == "") { echo "not filled in"; -include form again - exit; } I start cheching from the top of the form so as soon as an error is found it is displayed and the form redisplayed until the last validation passes and it is processed. Link to comment https://forums.phpfreaks.com/topic/28385-registration-validation/#findComment-728011 Share on other sites More sharing options...
DarkWater Posted January 2, 2009 Share Posted January 2, 2009 In my personal opinion, a nice, elegant way to handle validation of an entire POST or GET array is something like: <?php foreach ($_POST as $key => $value) { switch ($key) { case "name": case "password": case "email": if (strlen($value) < 4) { $errors->registerError(new FormError(ucfirst($key) . " was not properly filled in")); } break; case "captcha": if ($value != $_SESSION['captcha']) { $errors->registerError(new FormError('The entered code did not match the captcha.')); } break; default: break; } } Being able to use the ability for switch statements to cascade is very helpful here so you can group similar behaviors. You can ignore the $errors-> stuff, it's how my error collection class so I can iterate easily. You can replace that stuff with a simple $errors[] array or something. Link to comment https://forums.phpfreaks.com/topic/28385-registration-validation/#findComment-728015 Share on other sites More sharing options...
bahewitt Posted January 3, 2009 Share Posted January 3, 2009 Thanks darkwater I think switch would probably work better, as you noted, by grouping the validations together as most check for the same thing (null, length etc.) I guess I will be working on my registration script today. Have a good one Link to comment https://forums.phpfreaks.com/topic/28385-registration-validation/#findComment-728548 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.