for one property of my object (newPSW), I use a repeated type in the form builder.
$builder->add('NewPSW', 'repeated', array(
'type' => 'password',
'invalid_message' => 'blablabla',
'first_options' => array('label' => 'New password'),
'second_options' => array('label' => 'Confirm password'),
))
));
if I look at the code source the name of the two fields are newPSW[first] and newPSW[second]
Validating my form, I would like to add a custom error to NewPSW property.
For any other "normal" field, I would do this (and it works good) :
$error = new FormError("What I want to say");
$form->get('object Property name')->addError($error);
I tried to do the same thing with this field but the error message does not display.
Q1 What do I have to write in the 'get' method of the $form to add the error?
I tried this already :
$form->get('newPSW')->addError($error); (no error but nothing is displayed)
$form->get('newPSW[first]')->addError($error); (error : Child "newPSW[first]" does not exist)
You can provide custom error message for the second of the repeated field like this:
$form->get('NewPSW')->get('second')->addError(new FormError('Oops! This is error message for confirm field'));
Related
In my symfony2 project I created a new FormType which is called "ChoiceAndOrTextType" which is a list of choices (checkboxes) but the user can also check the "others" option and write his answer into a textfield.
The code is like this one here in the answer of bschussek:
Use a conditional statement when creating a form
$builder
->add('choice', 'choice', array(
'choices' => $options['choices'] + array('Other' => 'Other'),
'required' => false,
))
->add('text', 'text', array(
'required' => false,
))
->addModelTransformer(new ValueToChoiceOrTextTransformer($options['choices']))
;
Now i want to validate this correctly, so when the user checks "Others" then the textfield needs to be filled out, if "Others" isn't checked it can be blank. (Kind of dependent validation).
How do I do this?
You need to use two validation constraints, for example in validation.yml yaml file
My Db_NoRecordExists message is overwite by addErrorMessage.
Code:
$emailaddress = new Zend_Form_Element_Text('EmailAddress');
$emailaddress->setRequired(true)
->setAttrib('size', '30')
->addFilters(array('StringTrim', 'StripTags'))
->addValidator('EmailAddress',TRUE)
->setDecorators($decorators)
->addErrorMessage('Please Enter Va`enter code here`lid Values.')
->setAttrib('MaxLength',100)
->setAttrib('onkeyup','setUserName()')
->setAttrib('onkeypress','setUserName()')
->setAttrib('onfocus','setUserName()')
->setAttrib('onchange','setUserName()')
->setAttrib('Maxlength', '100');
$emailaddress ->class="textbox";
and
public function isValid($data)
{
$this->getElement('EmailAddress')
->addValidator('Db_NoRecordExists', false, array(
'table'=>'puntermaster',
'field' => 'EmailAddress',
'messages' => array(Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND => 'A user with email address already exists'),
'exclude' => array( 'field' => 'Sno', 'value' => $data['Sno'])
), TRUE);
return parent::isValid($data);
}
If you add a custom error message to your form element using addErrorMessage() or addErrorMessages() and one of the validators fails validation, then the custom error message will be used instead of the validator specific error message.
Only use addErrorMessage if you want to override all of the validator's error messages for a form element.
Another use of addErrorMessage is to call it after you've validated the form element and you want to add a custom message you later retrieve with getErrorMessages().
Is it possible to change the output of the matches call when running form validation in CodeIgniter?
I'm validating a password against a confirm password box.
array(
'field' => 'userPassword',
'label' => 'Password',
'rules' => 'trim|required|matches[userConfPassword]'
)
But when the error is triggered it prints out:
The Password field does not match the userConfPassword field.
The user has no idea was userConfPassword means and I'd like to change that to something more friendly. Reading the docs I can't find a way to do it.
Well, you can override the default message:
$this->form_validation->set_message('matches', 'the two passwords do not match|');
or some other message like that :).
I usually use that message for the "confirm password" only, though, so I set the normal password field as required and that's all, while for the confirm I have it to match the password entered, not the otherway around (or both). But that's just matter of taste I think.
For the record, it's written in this paragraph of the manual.
This code works for me:
array(
'field' => 'userPassword',
'label' => 'Password',
'rules' => 'trim|required|matches[userConfPassword]'
),
array(
'field' => 'userConfPassword',
'label' => 'Confirm Password',
'rules' => 'trim|required'
)
When the error is triggered it prints out:
The Password field does not match the Confirm Password field.
I have the following code:
$postcode = $form->createElement('text', 'postcode');
$postcode->setLabel('Post code:');
$postcode->addValidator('regex', false,
array('/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i'));
$postcode->addFilters(array('StringToUpper'));
$postcode->setRequired(true);
It creates an input field in a form and sets a regex validation rule and works just fine.
The problem is that the error message it displays when a user enters an invalid postcode is this:
'POSTCODE' does not match against pattern
'/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i'
(where input was POSTCODE)
How can I change this message to be a little more friendly?
I think to remember, you can set the error message in the Validator:
$postcode = $form->createElement('text', 'postcode');
$postcode->setLabel('Post code:');
$postcode->addValidator('regex', false, array(
'pattern' => '/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i')
'messages' => array(
'regexInvalid' => "Invalid type given, value should be string, integer or float",
'regexNotMatch' => "'%value%' does not match against pattern '%pattern%'",
'regexErrorous' => "There was an internal error while using the pattern '%pattern%'"
)
);
$postcode->addFilters(array('StringToUpper'));
$postcode->setRequired(true);
If that doesn't work, try
setErrorMessages(array $messages): add multiple error messages to display on form validation errors, overwriting all previously set error messages.
If you define your validator as external variable use setMessage():
$validator = new Zend_Validate_Alnum();
$validator->setMessage('My custom error message for given validation rule',
Zend_Validate_Alnum::INVALID);
$formElement->addValidator($validator);
As you see in example above validator for form doesn't differ from any other kind of Zend_Validate_* instances.
Setting up validation messages involves looking into API Docs and finding out message constant for a given validation error (as I did in case of Zend_Validate_Alnum::INVALID). Of course if your IDE provides good context auto-completion just typing the validator class can be enough - as message constants are really self-explanatory in most cases.
Another way would be to use Zend_Form's magic methods, and simply passing 'messages' key, as a parameter to your validator:
$formElement->addValidator(array(
'alnum', false, array('messages' => array(
Zend_Validate_Alnum::INVALID => 'my message'
))
));
This would internally trigger the setMessages() method defined in Zend_Validate_Abstract, and in essence just a short-cut/time-saver defined for Zend_Form's.
NB: There's a dedicated section in ZF Manual regarding validation messages.
You could use the original Zend postcode validator
$user->addElement('text', 'postcode', array('label' => 'Postcode *',
'required' => true,
'class' => 'postcode_anywhere',
"validators" => array(
array("NotEmpty", false, array("messages" => array("isEmpty" => "Required *"),)),
array('PostCode', false, array('locale' => 'en_GB')
)
),
'filters' => array(array('StringToUpper')),
'class' => 'text'
)
);
I'm using Zend Framework 1.62 (becuase we are deploying the finished product to a Red Hat instance, which doesn't have a hgih enough PHP version to support > ZF1.62).
When creating a Form using Zend Form, I add a select element, add some multi options.
I use the Zend Form as an in-object validation layer, passing an objects values through it and using the isValid method to determine if all the values fall within normal parameters.
Zend_Form_Element_Select works exactly as expected, showing invalid if any other value is input other than one of the multi select options I added.
The problem comes when I want to display the form at some point, I cant edit the error message created by the pre registered 'InArray' validator added automatically by ZF. I know I can disable this behaviour, but it works great apart from the error messages. I've tryed the following:
$this->getElement('country')->getValidator('InArray')->setMessage('The country is not in the approved lists of countries');
// Doesn't work at all.
$this->getElement('country')->setErrorMessage('The country is not in the approved lists of countries');
// Causes a conflict elswhere in the application and doesnt allow granular control of error messages.
Anyone have any ideas?
Ben
I usually set validators as per my example below:
$this->addElement('text', 'employee_email', array(
'filters' => array('StringTrim'),
'validators' => array(
array('Db_NoRecordExists', false, array(
'employees',
'employee_email',
'messages' => array(Zend_Validate_Db_Abstract::ERROR_RECORD_FOUND => 'A user with email address %value% already exists')
))
),
'label' => 'Email address',
'required' => true,
));
The validators array in the element options can take a validator name (string) or an array.
When an array is passed, the first value is the name, and the third is an array of options for the validator. You can specify a key messages with custom messages for your element in this array of options.
If your using Zend_Form_Element_Select (or any of the Multi subclasses), on validation the InArray validator will only be automatically added if there is not one present.
You can set a validator as so:
$options = array(...);
$this->addElement('select', 'agree', array(
'validators' => array(
array('InArray', true, array(
'messages' => array(
Zend_Validate_InArray::NOT_IN_ARRAY => 'Custom message here',
),
'haystack' => array_keys($options),
)),
'multiOptions' => $options,
));
and then your validator will be used instead of the automatically attached one.
$el = $this->addElement($name, $label, $require, 'select');
$validator = new Zend_Validate_InArray(array_keys(AZend_Geo::getStatesList()));
$validator->setMessage('Invalid US State.');
$el
->setMultiOptions(AZend_Geo::getStatesList())
->setRegisterInArrayValidator(false)
->addValidator($validator)
->addFilter(new Zend_Filter_StringToUpper())
->addFilter(new T3LeadBody_Filter_SetNull())
->setDescription('US State. 2 char.');