I used to have this form element to validate an email and display an error message if the format was invalid:
$email_users = new Zend_Form_Element_Text('email_users');
$email_users->setLabel('Email:')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('EmailAddress')
->setErrorMessages(array('messages' => 'Invalid Email'));
setErrorMessages worked fine because this was the only validation I needed so it replaced all error messages with my custom one, now I had to add another validation to see if it already existed in my DB:
$email_users = new Zend_Form_Element_Text('email_users');
$email_users->setLabel('Email:')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidators(array(
array('EmailAddress', true,
array(
'messages' =>
array(Zend_Validate_EmailAddress::INVALID => 'Invalid Email')
)
),
array('Db_NoRecordExists', true,
array(
'messages' =>
array(Zend_Validate_Db_NoRecordExists::ERROR_RECORD_FOUND => 'Email already exists'),
'table' => 'users',
'field' => 'email_users')
)));
The functionality is fine, the problem is that when the email is invalid it now shows me the default zend validate messages, ut when it exists it does show me my custom message. Is there any way to archive the previous functionality this way? (Replacing all invalid email messages) I can't uset setErrorMessages since this shows me 'invalid email' when the email alrady exists.
I tried using 'messages' => 'Error' but nothing happens (no errors but the default messages show), I tried:
$emailValidator = new Zend_Validate_EmailAddress();
$emailValidator->setMessages('Invalid email');
And on my form element I added
$email_users->addValidator($emailValidator)
Nothing same results. The closest I have gotten is doing 'messages' => array(Zend_Validate_EmailAddress::INVALID_FORMAT => 'Invalid email') this shows the msg when I type something like 'email#' or 'email' but if I type 'email#host' it shows me 3 erros regarding the hostname, dns and localnetwork, which they don't show when I use setMessages('Error') (just displays 'Error'),
Thanks in advance.
I posted an answer which explains how all the different error message setting functions work here,
Zend validators and error messages: addValidator and addErrorMessage
In short, try this:
'messages' => 'Email already exists'
instead of using an array.
You have to write validator like this..
$email_users->addValidator(
'EmailAddress',
true,
array( 'messages' => array( 'emailAddressInvalidFormat' => "Email Address is Not Valid... !<br>", "emailAddressInvalidHostname"=>"Email Address is Not Valid... !<br>", "hostnameUnknownTld"=>"Email Address is Not Valid... !<br>","hostnameLocalNameNotAllowed"=>"Email Address is Not Valid... !<br>") )
);
In all cases of invalid email address error must show "Email Address is Not Valid... !".
Related
I need to add some form validation for telephone field on admin side for magento. I am looking for correct file to work on
There's already some validation for required fields on the admin sales_order_create I am trying to find the right file that I can work on for the page sales_order_create. I did some search but still I had no luck on my code base.
You can use the following to class method for validating
'validate-phoneStrict' => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-phoneLax' => 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
And this can be use as follow:
$fieldset->addField('phone', 'text', array(
'label' => Mage::helper('foundation')->__('Phone'),
'class' => 'required-entry validate-phoneStrict',
'required' => true,
'name' => 'phone',
));
How can I overwrite Zend validation messages in my code below.
$validatee = array(
'email' => $email,
);
$validator = array(
'email' => array(
'EmailAddress',
'messages' => array('emailAddressInvalidFormat',"Invalid Email Address")
)
);
$emailValidator = new Zend_Filter_Input(null, $validator,$validatee);
I tried doing that but the message doesn't change and always output
"no valid email address in the basic format local-part#hostname"
please help!
Change your $validator to ::
can you try adding
$validator = new Zend_Validate_EmailAddress();
$validator->setMessage(
'A valid email is required',
Zend_Validate_EmailAddress::INVALID
);
and then use in Zend_filter_input?
I am facing an small issue regarding the Email Validation in my Zend Form.
My Code for the Email field is as
$emailId = new Zend_Form_Element_Text('email');
$emailId->setLabel("Email Adresse")
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator(new Validator_EmailValidator())
->addValidator('NotEmpty')
->addValidator(
'NotEmpty',
TRUE,
array('messages' => array(
'isEmpty' => 'Please enter your email id.'
)
)
);
Currently it is showing the Email Error Messages as :
What I want is to set a single error message in the place of all these errors and that is as :
"'abcd#shdsjah' is not a valid Email Id."
Since I am new to the Zend Framework, I don't have much idea about it, although I tried some code but they are useless.
Please help.....
Thanks In Advance....
When I was new to zend-framework, I faced this problem and got solution by using setErrors() method as:
//this will immediately call the method markAsError() which will show the error always
$emailId->setErrors(array('Please enter a valid Email Id.'));
You can also try :
//this will clearErrorMessages() and after that set the error messages
$emailId->setErrorMessages(array("Please enter a valid Email Id."));
Write this code after your code.
I hope it will be helpful to you......
Pass true as second argument of addValidator (breakChainOnFailure). The validation will stop at the first failure and you will have only have one error message.
I see that you are passing your own Custom Validator.
->addValidator(new Validator_EmailValidator())
You don't need to do that. Just use :
$validator = new Zend_Validate_EmailAddress()
Then just set that validator on the form item, and then set the messages against that validator.
So
$emailId->setValidator( $validator );
Now just set the Messages against the Validator, using the setMessages method.
These are all of the potential messages that you can change:
const INVALID = 'emailAddressInvalid';
const INVALID_FORMAT = 'emailAddressInvalidFormat';
const INVALID_HOSTNAME = 'emailAddressInvalidHostname';
const INVALID_MX_RECORD = 'emailAddressInvalidMxRecord';
const INVALID_SEGMENT = 'emailAddressInvalidSegment';
const DOT_ATOM = 'emailAddressDotAtom';
const QUOTED_STRING = 'emailAddressQuotedString';
const INVALID_LOCAL_PART = 'emailAddressInvalidLocalPart';
const LENGTH_EXCEEDED = 'emailAddressLengthExceeded';
Message Defaults
protected $_messageTemplates = array(
self::INVALID => "Invalid type given. String expected",
self::INVALID_FORMAT => "'%value%' is no valid email address in the basic format local-part#hostname",
self::INVALID_HOSTNAME => "'%hostname%' is no valid hostname for email address '%value%'",
self::INVALID_MX_RECORD => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
self::INVALID_SEGMENT => "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network",
self::DOT_ATOM => "'%localPart%' can not be matched against dot-atom format",
self::QUOTED_STRING => "'%localPart%' can not be matched against quoted-string format",
self::INVALID_LOCAL_PART => "'%localPart%' is no valid local part for email address '%value%'",
self::LENGTH_EXCEEDED => "'%value%' exceeds the allowed length",
);
Now just change the messages to whatever you want. You will need to update every message.
$validator->setMessages(array(
Zend_Validate_EmailAddress::INVALID => "Invalid type given, value should be a string",
Zend_Validate_EmailAddress::INVALID_FORMAT => "'%value%' is no valid email address in the basic format local-part#hostname",
Zend_Validate_EmailAddress::INVALID_HOSTNAME => "'%hostname%' is no valid hostname for email address '%value%'",
Zend_Validate_EmailAddress::INVALID_MX_RECORD => "'%hostname%' does not appear to have a valid MX record for the email address '%value%'",
Zend_Validate_EmailAddress::INVALID_SEGMENT => "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network.",
Zend_Validate_EmailAddress::DOT_ATOM => "'%localPart%' can not be matched against dot-atom format",
Zend_Validate_EmailAddress::QUOTED_STRING => "'%localPart%' can not be matched against quoted-string format",
Zend_Validate_EmailAddress::INVALID_LOCAL_PART => "'%localPart%' is no valid local part for email address '%value%'",
Zend_Validate_EmailAddress::LENGTH_EXCEEDED => "'%value%' exceeds the allowed length",
));
How can i get rid of Zend default error not to show "Value is required and can't be empty"
Thanks
I'm using this method:
$this->addElement(
'text',
'testname',
array(
'label' => 'User Name',
'required' => true,
'filters' => array(
'StringTrim'
)
)
);
If you need to change the actual message text then use something like this:
$field = new Zend_Form_Element_Text('field');
$field ->setRequired(TRUE)
->addValidator(
'NotEmpty', //validator name
FALSE, //do not break on failure
array(messages' => array(
'isEmpty' => 'INSERT CUSTOM MESSAGE HERE'
)
)
)
Here you change the 'isEmpty' message of the NotEmpty validator.
Or if you defined the element differently.
$element = $this->getElement('text');
$element->addValidator('NotEmpty', //validator name
FALSE, //do not break on failure
array(messages' => array(
'isEmpty' => 'INSERT CUSTOM MESSAGE HERE'
)
)
)
In Zend_Form this is the default error message of the default validator 'Empty'.
To remove this validator, on the element add the removeValidator() function with 'empty' as the parameter:
$element->removeValidator('Empty');
This is assuming you have made a form in Zend_Form, that you have POSTed an empty value and are trying to validate it?
Going forward, please provide more information.
I have the following code to generate an input field for user's email address
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress')
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
)))
->setRequired(true)
->setDecorators(array(
array('Label', array('escape'=>false, 'placement'=>'append')),
array('ViewHelper'),
array('Errors'),
array('Description',array('escape'=>false,'tag'=>'div')),
array('HtmlTag', array('tag' => 'div')),
));
$this->addElement($email);
now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin#l' as email address, and the errors will be
* 'l' is no valid hostname for email address 'admin#l'
* 'l' does not match the expected structure for a DNS hostname
* 'l' appears to be a local network name but local network names are not allowed
I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.
Well, it's a late answer but I think is always useful.
Simply add true as second param of addValidator()
From Zend docs (http://framework.zend.com/apidoc/1.8/):
addValidator (line 67)
Adds a validator to the end of the chain
If $breakChainOnFailure is true, then if the validator fails, the next
validator in the chain, if one exists, will not be executed.
return: Provides a fluent interface
access: public
Here the signature:
Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])
Zend_Validate_Interface $validator
boolean $breakChainOnFailure
So the code is:
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress', TRUE ) // added true here
->addValidator(new Zend_Validate_Db_NoRecordExists(
array(
'adapter'=>Zend_Registry::get('user_db'),
'field'=>'email',
'table'=>'tbl_user'
), TRUE )
);
You have to create an instance of the Zend_Validate_EmailAddress class and call the setMessages method and then override the messages that you like, to remove the ones that you mention it would be something like this:
$emailValidator->setMessages(array(
Zend_Validate_EmailAddress::INVALID_FORMAT => "Your error message",
Zend_Validate_Hostname::INVALID_HOSTNAME => "Your error message",
Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED => "Your error message"
));
I hope this help somebody :-)
$email->addErrorMessage("Please Enter Valid Email Address");
you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project
class Validate_Email extends Zend_Validate_Abstract
{
const INVALID = 'Email is required';
protected $_messageTemplates = array(
self::INVALID => "Invalid Email Address",
self::ALREADYUSED => "Email is already registered"
);
public function isValid($value)
{
if(preg_match($email_regex, trim($value))){
$dataModel = new Application_Model_Data(); //check if the email exists
if(!$dataModel->email_exists($value)){
return true;
}
else{
$this->_error(self::ALREADYUSED);
return false;
}
}
else
{
$this->_error(self::INVALID);
return false;
}
}
}
and in you form.php file
$mailValidator = new Validate_Email();
$email->addValidator($mailValidator, true);
Don't know if it works or not but for me it worked in case of telephone. Courtesy of http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/
It seems to be missing quite a few lines...
probably should use this:
$mailValidator = new Zend_Validate_EmailAddress();
you can also do some other validations see here: http://framework.zend.com/manual/en/zend.validate.set.html
Using a custom validator is the only way I found to avoid this problem.
If what you want is:
Having only one error message if the email address is in a wrong format
If the format is good, then validate if the email address is already in the database
Then I suggest you to do something like this:
$where = array('users', 'email', array('field' => 'user_id',
'value' => $this->getAttrib('user_id')));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail:')
->setRequired(true)
->setAttrib('required name', 'email') // html5
->setAttrib('maxlength', '50')
->addFilter('StripTags')
->addFilter('StringTrim')
->addFilter('StringToLower')
->addValidator('email', true)
->addValidator('stringLength', true, array(1, 50))
->addValidator('db_NoRecordExists', true, $where)
->addDecorators($this->_elementDecorators);
$this->addElement($email);
$this->getAttrib('user_id') represents the current user's id.
There are three validators here, all of them have their second parameter $breakOnFailureset to false, so if a validator fails, the other ones won't be called.
The first validator is email, which is my own custom validator:
class My_Validate_Email extends Zend_Validate_EmailAddress
{
public function getMessages()
{
return array('invalidEmail' => 'Your email address is not valid.');
}
}
You can add this validator in your library, in /application/library/My/Validate for example, and then add
$this->addElementPrefixPath('My_Validate', 'My/Validate', 'validator');
into your form. Of course, you need to replace "My" by the name of your library.
Now if an email is in the wrong format, it will always display 'Your email address is not valid.'. If your email is too long and doesn't fit into your database field (VARCHAR(100) for example), it's going to show your stringLength validator errors, and in the last case, if an entry already exists in the database, only this error will be shown.
Of course you can add more methods into your custom validator and overload setMessages, so that you can display your own messages whatever the form you are working on.
Hope it can help someone!