CodeIgniter Forums
Custom validation rules? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Custom validation rules? (/showthread.php?tid=5373)



Custom validation rules? - El Forum - 01-19-2008

[eluser]RyanH[/eluser]
I'd like to create some custom validation rules, but I'm not sure how. The most important rule I want to create is to specify the email address. I want someone's email address to match only certain domains. For example, I only want email addresses that are coming from Gmail. [email protected] would work, but [email protected] would not. Any advice? Thanks. Smile


Custom validation rules? - El Forum - 01-19-2008

[eluser]Pascal Kriete[/eluser]
Something like this might work:
Code:
$parts = explode("@", $email);
$domain = $parts[1];

//Check if $domain is in list of allowed domain - using an array here
if (! in_array($domain, $allowed_array))
    //error
else
   //Yay



Custom validation rules? - El Forum - 01-19-2008

[eluser]xwero[/eluser]
Code:
class MY_Validation extends CI_Validation
{
function domain_email($str,$params)
{
   $parts = explode("@", $str);
   $domain = $parts[1];
   $allowed_array = explode(',',$params);
   //Check if $domain is in list of allowed domain - using an array here
   return in_array($domain, $allowed_array);
}
}
Use rule
Code:
$rules['email'] = 'valid_email|domain_email[gmail.com]';



Custom validation rules? - El Forum - 01-19-2008

[eluser]RyanH[/eluser]
Thanks! Where do I put this new class?


Custom validation rules? - El Forum - 01-19-2008

[eluser]xwero[/eluser]
in the libraries directory


Custom validation rules? - El Forum - 01-19-2008

[eluser]mironcho[/eluser]
Hi RyanH,
If you don't prefer creating new class, you might create callback function in your controller - simply put xwero's domain_email function in your controller and use it in your rules in this manner:

Code:
$rules['email'] = 'valid_email|callback_domain_email[gmail.com]';



Custom validation rules? - El Forum - 01-19-2008

[eluser]RyanH[/eluser]
[quote author="mironcho" date="1200805002"]Hi RyanH,
If you don't prefer creating new class, you might create callback function in your controller - simply put xwero's domain_email function in your controller and use it in your rules in this manner:

Code:
$rules['email'] = 'valid_email|callback_domain_email[gmail.com]';
[/quote]Thanks, I think this will work much easier for me.

Also, how do I go about creating a validation rule that allows spaces? I want to allow only alpha numeric, or just numeric, but also contain spaces. For example, a state name may have two words such as New York, but when you use the alpha or alpha_numeric rule, that returns false.