So searched the internet and stackoverflow to find anything related that could have been discussed before or any article, i was unable to find any, so i found myself creating the topic.
I am working on a project where i make a lot of ajax request on POST. Therfor validation plays an important role as it MUST be.
So i created some Validation functions as listed below
//only numeric (integer) regexp [1-9]
Validation::isInteger($a);
//numeric and alphabetic (integer&string) regexp [a-z1-9]
Validation::isAlphaNum($c);
//(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday) Regexp
Validation::isDay($d);
//Array numeric (integer) Regexp
Validation::isArrayNum($sortTo);
I used it in my code like this, But this seems so ugly! in Model:
if(Validation::isInteger($a))
{
if(Validation::isAlphaNum($c))
{
if(Validation::isDay($d))
{
if(Validation::isArrayNum($sortTo))
{
//do process here!
}}}}
Then i thought about doing validation like this maybe; Not sure if its safe! in Model:
if(!Validation::isInteger($a) &&
!Validation::isAlphaNum($c) &&
!Validation::isDay($d) &&
!Validation::isArrayNum($sortTo)) exit;
//do process here anyway without "if" closure if you dont pass validation above you won't see me!
My questions are:
- Should i validate data in Controller or model? Does it matter?
- Is my second approach safe?
- How do you validate your data? (whats your design of code)
- What other methods/techniques i can use to prettify this uglyness.
NOTE: i am not too concerned about throwing errors due to validation fails.
EDIT:(23.02.2014) However i found a video that has great explanations about Validation by phpacademy in youtube.com if you are having same kind of problems with validation or want to have an idea i really recommend you watch it. http://www.youtube.com/watch?v=rWon2iC-cQ0&index=13&list=PLfdtiltiRHWF5Rhuk7k4UAU1_yLAZzhWc