ZF2 - Need to display specific error message on specific condition failure - php

I am using ZF2 form validation.I have to validate two fields USERNAME and PASSWORD.
everything is working fine but I am getting message like
Please enter username.
Username can not be less than 3 characters.
Please enter password.
Password can not be less than 6 characters.
If user is not entering any value then only this message should display
Please enter username.
Please enter password.
I don't want do display all the error messages on a field on failure.
Thanks in advance.

I got the answer :
In order to break the validation chain in ZF2 , we have to use
'break_chain_on_failure' => true
$this->add(
array(
'name' => 'usernmae',
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim')
),
'validators' => array(
array('name' => 'NotEmpty',
'options' => array('encoding' => 'UTF-8',
'messages' => array(
NotEmpty::IS_EMPTY => 'Please enter username')),
'break_chain_on_failure' => true),
array(
'name' => 'Zend\Validator\StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 3,
'max' => 30,
'messages' => array(
StringLength::TOO_LONG => 'Username can not be more than 30 characters long',
StringLength::TOO_SHORT => 'Username can not be less than 3 characters.')
),
'break_chain_on_failure' => true
)
)
)
);
My Blog : http://programming-tips.in

Zend_Validate allow you to break validators chain if certain vaildation fails. The second parameter of addValidator() function $breakChainOnFailure should be TRUE in this case.
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(new Zend_Validate_NotEmpty(), TRUE)
->addValidator(new Zend_Validate_StringLength(6, 12));

You can also set the 'error_message' key, for example:
'email' => [
'required' => true,
'error_message' => 'Incorrect email address ',
'filters' => [
[
'name' => 'StripTags',
],
[
'name' => 'StringToLower',
]
],
'validators' => [
[
'name' => 'EmailAddress',
'break_chain_on_failure' => true
]
]
],

Related

Cakephp, validate field if not required

Hi i encounter strange problem, i have this input in my form
$this->Form->input('processing_data', array('label' => 'STH', 'required' => 'required'));
and this produces this html
<input id="UserProcessingData" type="checkbox" value="1" required="required" name="data[User][processing_data]">
my model validating this field is User model and code of it :
'processing_data' => array(
'rule' => 'notEmpty',
'allowEmpty' => false,
'message' => 'Prosze zaznaczyć'
),
but let's say someone manually delete required="required" from input and then validation is not triggered i thought 'rule => 'notEmpty' will do but nothing changed so next i added 'allowEmpty' => false, but also it didn't help.
What can be done to validate this field even if required is not present
Use this-
'processing_data' => array(
'rule' => array('notEmpty'),
'required' => true,
'message' => 'Prosze zaznaczyć'
),
use required => true in model and you can true your allowEmpty validation if it is mandatory.
'processing_data' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => true,
'message' => 'Prosze zaznaczyć'
),
try this
'processing_data' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Prosze zaznaczyć'
),

Validation "blank" or "empty" in cakephp Form

I just created a form in cakephp and I would like to do a validation for one of the field.
The form will only be submitted if this particular field is left empty.
Here's a my particular field
<?php echo
$this->Form->input('MyForm.fieldA', array(
'type' => 'text',
'label' => '',
'class' => 'span3 detector-form',
))
?>
And my validation code:
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'submit',
'message' => 'Failed authorize',
'last' => true
),
);
P/s. I tried using
public $validate = array(
'fieldA' => array(
'rule' => 'blank',
'on' => 'create',
'message' => 'Failed authorize',
'last' => true
),
);
But the 'create' sounds like only worked when the field is created.So I changed to 'submit' for a testing purpose.
I tried to use rule''=> 'Empty' as well but the validation doesn't work. Or is there any other alternative rules that I can use to reach this goal?

How to validate multiply select using Zend Framework 2

I am trying to validate a multiply select using input filter, but every time I see a error. The error is "notInArray":"The input was not found in the haystack".(I use ajax but it doesn`t metter).
I will show part of my code to be more clear.
in Controller:
if ($request->isPost()) {
$post = $request->getPost();
$form = new \Settings\Form\AddUserForm($roles);//
$form->get('positions')
->setOptions(
array('value_options'=> $post['positions']));
//.... more code...
When I put print_r($post['positions']); I see:
array(0 => 118, 1 => 119)
in ..../form/UserForm.php I create the multiply element
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
and in the validation file the code is:
$inputFilter->add($factory->createInput(array(
'name' => 'positions',
'required' => false,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => array(118,119),
'messages' => array(
'notInArray' => 'Please select your position !'
),
),
),
),
What can be the reason every time to see this error, and how I can fix it?
By default selects have attached InArray validator in Zend Framework 2.
If you are adding new one - you will have two.
You should disable default one as follow:
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'options' => array(
'disable_inarray_validator' => true, // <-- disable
),
'attributes' => array(
'multiple' => 'multiple',
'id' => 'choosed_positions',
),
'required' => false,
'name' => 'positions',
));
And you should get rid of the additional error message.
Please let us know if that would helped you.

Custom validation rule in CakePHP not working as intended

I wrote a custom validation method inside my Submission model that basically allows a blank input field, but once someone enters something in it, it'll validate the data entered.
The validation inside my Submission Model looks like this (All other validation rules are working except for 'description'):
var $validate = array(
'title' => array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a title'
),
'minLength' => array(
'rule' => array('minLength', 5),
'message' => 'Please make your title longer'
),
'maxLength' => array(
'rule' => array('maxLength', 300),
'message' => 'Your title needs to be shorter'
),
),
'description' => array(
'checkDescription' => array(
'rule' => array('validateDescription'),
'message' => 'Description must be greater than 5 characters'
),
),
'source' => array(
'source' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Enter a valid source URL'
),
'website' => array(
'rule' => 'url',
'message' => 'Please enter a valid source URL'
),
)
);
My method which is also in my Submission model (below the above code) is:
public function validateDescription($data) {
if(empty($data['Submission']['description']))
return true;
if((strlen($data['Submission']['description'])) <= 5)
return false;
}
I'm not sure why this isn't working at all. In my view, I've got this to display the error:
if ($form->isFieldError('Submission.description'))
echo ($form->error('Submission.description', null, array('class' => 'error')));
The only reason I'm trying to do this, is because using the normal validation with required => false and allowEmpty => true along with a minLength and maxLength validation rule weren't behaving how I intended.
Any help would be greatly appreciated! :)
The $data variable passed into the validation method only contains array($fieldname => $value). You're also not returning true for strings over length of 5. Your method should look like this:
public function validateDescription(array $data) {
$value = current($data);
return !$value || strlen($value) > 5;
}

CakePHP why am I getting this error?

Here is the error message:
Warning (2): preg_match() [http://php.net/function.preg-match]: Delimiter must not be alphanumeric or backslash [CORE/cake/libs/model/model.php, line 2611]
This is happening when I call the following code from my controller:
$this->Account->save($this->data)
The model looks like this:
class Account extends AppModel
{
var $validate = array(
'first_name' => array(
'rule' => array('minLength', 1),
'required' => true
),
'last_name' => array(
'rule' => array('minLength', 1),
'required' => true
),
'password' => array(
'rule' => array('minLength', 8),
'required' => true
),
'email' => array(
'emailRule1' => array(
'rule' => 'email',
'required' => true,
'message' => 'You must specify a valid email address'
),
'emailRule2' => array(
'rule' => 'unique',
'message' => 'That email address is already in our system'
)
)
);
}
I found a similar problem explained here
He solved it by changing required' => true to required' => array(true) I tried that for every occurange in my model but it did not fix the problem.
The problem was I named the rule unique it should be isUnique instead.
I would have figured this out much faster with a better error message.

Categories