Add special validation for some fields on signup form
Add this code to site.php file:
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['email']) && ($vars['email'] != 'test')) { // perform some validation
$e->addError('Some Error Occur!');
}
});
Example of code to allow registration only with gmail.com and hotmail.com email addresses:
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['email'])
&& preg_match('/.*?@(.*)$/i', $vars['email'], $m)
&& !in_array($m[1], ['gmail.com', 'hotmail.com'])) {
$e->addError('Only email address [gmail.com, hotmail.com] is allowed');
}
});
Example of code to validate Age on signup form
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['birthdate']) && $vars['birthdate']) {
$bd = new DateTime($vars['birthdate']);
$n = new DateTime;
$i = $n->diff($bd);
if ($i->y < 18) {
$e->addError("We do not accept user below the age of 18");
}
}
});
Example of code to disallow sign up from countries other than UK
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
$user = Am_Di::getInstance()->auth->getUser();
$country = $vars['country'] ?? ($user ? $user->country : null);
if ($country !== 'GB') {
$e->addError("Due to tax issue with Brexit we temporarily do not accept payments from countries other then UK");
}
});
Example of code to validate Phone on signup form
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['phone']) && !preg_match('/^[0-9]{11}$/', $vars['phone'])) {
$e->addError("Phone can contain only Numbers and exactly 11 digits");
}
});
Example of code to disallow signups with same first and last name (usually spam signups)
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['name_f']) && isset($vars['name_l']) && $vars['name_f'] == $vars['name_l'])
{
$e->addError('Some Error Occurred! Please try to signup later...');
}
});
Example of code to disallow signups with one letter first name (usually spam signups)
Am_Di::getInstance()->hook->add(Am_Event::VALIDATE_SAVED_FORM, function (Am_Event_ValidateSavedForm $e) {
/** @var HTML_QuickForm2 $form */
$form = $e->getForm();
$vars = $form->getValue();
if (isset($vars['name_f']) && strlen($vars['name_f']) < 2)
{
$e->addError('First Name should be at least two letters long');
}
});