Im having trouble with Yii1 validation. I have listbox with contact types and i want email validation to work only when contact via email is choosed. So Im using custom rule to check if its not empty:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "") $this->addError($attribute, "Enter email address");
}
}
}
But after that I want to use second rule to check if email format is good, how i can achieve it? In main rules i can check it by this:
['email', 'email', 'message' => 'wrong email format'],
but how i can check it only when $this->contact_type == 2 ? I need to write custom rule also and I need to write regex to check email format? Or somehow i can use main validation rules in custom validations?
Thank you.
First remove email validator from rules().
Using your same code, in your custom validation, you can 'attach' any existing Yii validator or create your own / custom validator. In your case, Yii email validator is enough and we will attach it to your custom validation:
public function customEmailValidation($attribute, $params)
{
if(!$this->hasErrors())
{
if($this->contact_type == 2)
{
if($this->attribute == "")
{
$this->addError($attribute, "Enter email address");
}
if( strlen($this->attribute) > 0 )
{
$emailValidator = new CEmailValidator;
if ( ! $emailValidator->validateValue($this->attribute) )
{
$this->addError($attribute, 'Wrong email');
}
}
}
}
}
Related
This is my validation for updating the email..
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__unique_email[email]');
The call back function is
public function _unique_email($email) {
if ($this->crud_model->fetch_user_by_email_user_id($email,$this->session->userdata('user_id'))) {
return true;
} else {
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
return true;
return false;
}
}
the email should be updated if the user changes the email in profile settings but if the user not makes any changes the email should be the old one and if he changes the email then it should be update by checking weather the email is unique in the database or not??
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|callback_email_check');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('form');
}
else
{
if($this->update($email)){
$this->load->view('formsuccess');
}
}
}
I haven't used codeIgniter for years, So I don't exactly know how things are there. But I'll try to answer your question on a general context and try to express that using the same code in your question with minor changes.
When You want to check if the user changed his email or not you need to have his old email from database first or in a hidden field of the form, then compare the email field value with the old one will make you know if he changed it.
Second you need to check if the email have duplicates on the database, remember you need to do this only if the user changed his email address, so just run a query with the database. if there are no existing email update the user email in database else display an error and quit.
public function is_unique_email($email) {
$old_email = $this->crud_model->fetch_user_email($this->session->userdata('user_id'));
if ($old_email == $email) {
return true;
} else {
$duplicates = $this->crud_model->fetch_user_by_email($email);
if(count($duplicates) > 0)
{
return false;
}
else
{
return true;
}
}
}
The end code should something similar to this, I'm sorry I can't give you the exact code, But I think you can run with this approach.
I suggest you to move to some good frameworks like symfony, laravel or
zend. Codeigniter is not improved much from those early days where PHP
did a lot.
I have a Yii form accept first name, last name and email from user. Using an add more link, users can add multiple rows of those three elements.
For email validation, unique and required are set in model rules and everything works fine. I am using JavaScript to create addition row on clicking add more link.
Problem
On the first row my values are John, Newman, johnnewman#gmail.com and the second row, i'm entering Mathew, Heyden, johnnewman#gmail.com. In this case email address is duplicated. None of the validation rules (require and unique) is capable of validating this. Can some one suggest a better method to validate this ?
Update:
I created a custom validation function and i guess this is enough to solve my problem. Can someone tell me how to access the whole form data / post data in a custom validation function ?
public function uniqueOnForm($attribute){
// This post data is not working
error_log($_REQUEST, true);
$this->addError($attribute, 'Sorry, email address shouldn\'t be repeated');
}
You can try this:
<?php
public function rules()
{
return array(
array('first_name', 'checkUser')
);
}
public function checkUser($attribute)
{
if($this->first_name == $this->other_first_name){
$this->addError($attribute, 'Please select another first name');
}
}
?>
You can also look into this extension
You can write custom validator:
//protected/extensions/validators
class UniqueMailValidator extends CValidator
{
/**
* #inheritdoc
*/
protected function validateAttribute($object, $attribute)
{
$record = YourModel::model()->findAllByAttributes(array('email' => $object->$attribute));
if ($record) {
$object->addError($attribute, 'Email are exists in db.');
}
}
}
// in your model
public function rules()
{
return array(
array('email', 'ext.validators.UniqueMailValidator'),
...
Or better try to use THIS
public function rules(){
return array(
//other rules
array('email', 'validEmail'),
)
}
public function validEmail($attribute, $params){
if(!empty($this->email) && is_array($this->email)){
$isduplicate = $this->isDuplicate($this->email);
if($isduplicate){
$this->addError('email', 'Email address must be unique!');
}
}
}
private function isDuplicate($arr){
if(count(array_unique($arr)) < count($arr)){
return true;
}
else {
return false;
}
}
because you are using tabular input (multiple row) , so make sure input field as an array. might be like this :
<?php echo $form->textField($model, 'email[]'); ?>
I have a simple registration form with an address-entity.
I do validate the value of each property using the loadValidatorMetadata(...) {...} method.
I want to check if the email is valide (by characters, etc...) and if email1 is equal to email2 and email1 hasn't to be in the bad-index-array.
Setting the validation is easy. But how can I define different errors-messages for each case?
code example:
public $email;
public $email2;
static function loadValidatorMetadata(ClassMetadata $metadata)
{
...
$metadata->addGetterConstraint('email', new Assert\False(array(
'message' => 'validation.addressFormEmail'
)));
...
}
public function getEmail()
{
if ($this->email == $this->email2) {
return false;
}
return false;
}
Symfony2 has a repeated form type where you can set your message if the value isn't repeated.
then in your entity validation you can set a custom message for email validation.
http://symfony.com/doc/current/reference/forms/types/repeated.html#validation
http://symfony.com/doc/current/reference/constraints/Email.html
how to validation email only use domain #gm.ac.id. i try but validation its not working.
this is code
public function email_check($email)
{
if (valid_email('email#mail.ugm.ac.id'))
{
return TRUE;
}
else
{
$this->form_validation->set_message('email_check', '%s gunakan email ugm');
return FALSE;
}
}
$this->form_validation->set_rules('email', 'email', 'required|callback_email_check');
please help me what to do.
thank you.
Valid_email has no way of knowing what domains it should allow or not.
An easier way would be:
$this->form_validation->set_rules('email', 'email', 'required|valid_email|callback_email_check');
This way you pass to email_check() only those emails which are validly constructed. Now you are just left to check the domain. Something like:
public function email_check($email)
{
return strpos($email, '#gm.ac.id') !== false;
}
I have made an email validation.
$this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email|callback_email_check');
function email_check($str)
{
if (stristr($str,'#uni-email-1.com') !== false) return true;
if (stristr($str,'#uni-email-2.com') !== false) return true;
if (stristr($str,'#uni-email-3.com') !== false) return true;
$this->form_validation->set_message('email', 'Please provide an acceptable email address.');
return FALSE;
}
After submitting my form, it says "Unable to access an error message corresponding to your field name." is there something wrong with my code?
it should be
$this->form_validation->set_message('email_check', 'Please provide an acceptable email address.');
go to documentation for reference HERE
To set your own custom message you can use the following function:
$this->form_validation->set_message('rule', 'Error Message');
but you haven't named the rule correctly in your code it should be email_check instead of email
$this->form_validation->set_message('email_check', 'Please provide an acceptable email address.');