I can change form validator error message by these code in my model:
array('name, email, subject, body', 'required'
'message'=>'Please enter a value for {attribute}.'),
but i don't know where the {attribute} came from and how can i change it for each field, so any help would be appreciated.
I'm not sure if i understand your question right, but you asked where the {attribute} came from:
Some validators introduce placeholders like the {attribute} in your example. If validation fails, they will be replaced with the attribute name. So if no name was entered and your message is 'Please enter a valid {attribute}.' the error message will be "Please enter a valid name".
While the {attribute} placeholder can be used with every validator, some of them introduce even more placeholders. For example with the CStringValidator you can use {min}, {max} or {length}. They will be replace with the number of minimum, maximum or exact characters respecitvely.
Here's an example:
array('firstname,lastname', 'string', 'min'=>3,
'tooShort'=>'Your {attribute} must contain at least {min} letters.'
),
This will give "Your firstname must contain at least 3 letters." if the users enters less than 3 letters. This has the advantage that if you change the min parameter, your message will automatically be updated. So it's less error prone.
Use these :
return array(
// name, email, subject and body are required
array('name', 'required',
'message'=>'Please enter a value for name.'),
array('email', 'required',
'message'=>'Please enter a value for email.'),
array('subject', 'required',
'message'=>'Please enter a value for subject.'),
array('body', 'required',
'message'=>'Please enter a value for body.'),
The {attribute} is taken from your function:
public function attributeLabels() {
return array(
'id' => 'ID',
'name' => 'Name',
'password' => 'Password',
'email' => 'Email',
);
}
on your model.
Related
I have created a controller to validate and save a form.
I don't know how the individual form fields are named because this is assigned by the system in the form designer.
For this reason I first make a query ($valArrays) to find out which fields are required and then find out what the array key is.
The field order_title is always required.
$valArrays = FormDetail::where('form_details.form_id', $request->form_id)
->where('required', 'yes')
->get();
$array = array();
$array['order_title'] = 'required';
foreach ($valArrays as $valArray) :
$array[$valArray->detail_id] = 'required';
endforeach;
$request->validate($array);
when I query via dd($array) I get the following evaluation:
^ array:6 [▼
"order_title" => "required"
"QS0brKe5LP" => "required"
"TjFusWAKLh" => "required"
"uNqAPbNwkg" => "required"
"OvclFtOlvF" => "required"
"52e515mfRf" => "required"
]
so everything is ok! but the programme jumps back to the form without saving.
If I take out the code part everything works but without validation :0(
Do you have any idea why this could be?
This is my model:
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
if ($this->scenario == "insert") {
return array(
array('requisition_id, sync', 'numerical', 'integerOnly' => true),
array('lastname, firstname, email, dob, phone, cv_path, experienceMonths, experienceYears, competencies, token', 'required', 'message' => "Câmpul este obligatoriu"),
array('email', 'email', 'message' => "Emailul este invalid!"),
array('dob', 'validateDob'),
array('dayOfBirth, monthOfBirth, yearOfBirth', 'safe'),
array('taleo_id, sync', 'required', 'on' => 'taleoUpdate'),
array('verifyCode', 'on' => 'insert'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
);
} else if ($this->scenario == 'taleoUpdate') {
return array(
array('taleo_id, sync', 'required'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
);
}
else if($this->scenario == 'notjobapply'){
return array(
array('lastname, firstname, email, phone, cv_path, requisition_id', 'required', 'message'=>'Câmpul este obligatoriu'),
array('email', 'email', 'message' => "Emailul este invalid!"),
);
}
return array(
array('id, lastname, email, phone, dob, requisition_id, experienceMonths, experienceYears, sync, cv_path, created', 'safe', 'on' => 'search'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>'captchaRequired'),
);
}
My problem is that it does not validate the letters from the image. I don't know why. I think that my validation is not correct in the rules. Anyone any clues?
Yes you have a lot of scenarios and applying different rules to them.
Make sure that the scenario that you're currently running does have a validation rule.
I can see that you use scenarios in two ways, one is the conditions you're using that I'm not fully sure they work, but maybe they do.
And the second is the Yii way, by specifying in the 'on' attribute in every rule declaration.
I would recommend writing all the rules again from scratch in this structure:
return array(
// scenarioA
array('field1, field2', 'required', 'on' => 'scenarioA'),
array('field1, field2', 'required', 'on' => 'scenarioA'),
array('field1, field2', 'required', 'on' => 'scenarioA'),
// scenarioB
array('field3, field4', 'required', 'on' => 'scenarioB'),
array('field3, field4', 'required', 'on' => 'scenarioB'),
array('field3, field4', 'required', 'on' => 'scenarioB'),
// scenarioC
array('field5, field6', 'required', 'on' => 'scenarioC'),
array('field5, field6', 'required', 'on' => 'scenarioC'),
array('field5, field6', 'required', 'on' => 'scenarioC'),
);
Or you could keep your condition blocks solution if you test that they behave correctly, but in that case you should remove the 'on' parameter from the rules inside the blocks.
Because for example here:
if ($this->scenario == "insert") {
return array(
...
array('taleo_id, sync', 'required', 'on' => 'taleoUpdate'),
You're putting code inside the condition where you verify that scenario is 'insert' but then again you specify the 'on' that will make that rule only be applied on 'taleoUpdate' scenario so it makes no sense.
Oh and as for the captcha, as you can see with your format you only reach the rule for it if the scenario is different from those you've specified above.
I've had a working registration/update model, I wanted to expand on my models so I added in a regex to the password field. I have checked the regex works online and even my client side validation shows it works, but the model refuses to save now. I'm not really sure why, could anyone help me out please?
return array(
array('firstName, lastName, email, password', 'required'),
array('firstName', 'length', 'max'=>45),
array('lastName', 'length', 'max'=>80),
array('email', 'length', 'max'=>120),
// email must be valid email
array('email', 'email'),
// email must be unique
array('email', 'unique'),
// Regex for password
array('password','match', 'pattern'=>'/^[a-z0-9_-]{7,20}$/i',
'message'=>'The password must be between 7 and 20 characters
long'),
array('password', 'length', 'min'=>7, 'max'=>64),
array('date_modified', 'safe'),
array('active, date_modified', 'default', 'setOnEmpty' => true, 'value' => null),
array('id, first_name, last_name, email, pass, active, date_created, date_modified, live', 'safe', 'on'=>'search'),
);
Thanks
Jonny
You can create your own validation rule.
http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/
Or else you can define validation rule in YII Model, something like this:
return array(
array('password', 'length', 'min'=>7, 'max'=>64),
array('password','pattern'=>'/^[A-Za-z0-9_!##$%^&*()+=?.,]+$/u', 'message'=>'Spaces or given characters are not allowed'),
);
There are more validation you can specify in your model.
Hi can you please tell how can i validate the multiple checkbox any one is checked in yii framework
array('accept', 'required', 'requiredValue' => 1, 'message' => 'You should select alteast one')
As these value are usually sent as arrays, I wrote an array validator for these cases once: https://github.com/schmunk42/p3extensions/blob/master/validators/P3ArrayValidator.php
Usage example:
array('accept',
'ext.validators.P3ArrayValidator',
'min'=>1,
'allowEmpty'=>false,
'message' => 'You should select at least one'
),
sorry for the late reply.
But, I found a solution without installing any extension.
Take a hidden field with the same name [Checkboxes list field].
<?php echo $form->hiddenField($model,'categories');?>
Display a list of categories with name different from our field name (multiple checkboxes).
But, remember the 'class', and play with the class to save the values.
<?php
echo CHtml::checkBoxList(
'group',
//you can pass the array here which you want to be pre checked
explode(',', trim($model->attributes['categories'], ',')),
CHtml::listData(Category::model()->findAll(),'id','name'),
array('separator'=>'', 'template'=>'<tr><td style="width:5%;">{input}</td><td>{label}</td></tr>', 'class' => 'group')
);
?>
This way validation should work also, you get category ids as comma separated e.g. [,1,2,6,]
<script>
$(function(){
$(".group").click(function(){
var str = $('.group:checked').map(function() {
return this.value;
}).get().join();
var groupCats = (str.length > 0) ? ','+str+',' : '';
$('#ModelNAME_field').val(groupCats);
// Get the 'ModelNAME_field' by viewing source of HTML of hidden field.
});
});
</script>
I had write the following code in my Zend Form:
$newpassword = new Zend_Form_Element_Password('newpassword');
$newpassword->setLabel("Enter your New Password :")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator(
'NotEmpty',
TRUE,
array('messages' => array(
'isEmpty' => 'Please enter new password.'
)
)
)
->addValidator(
'Alnum',
TRUE,
array('messages' => array(
'alnumInvalid' => 'Please enter a valid new password.',
'notAlnum' => 'Please enter a valid new password.',
'alnumStringEmpty' => 'Please enter a valid new password.'
)
)
)
->addValidator('StringLength', false, array(4, 25))
->getValidator('StringLength')->setMessage("Should be 4-25 characters long.");
$retypepassword = new Zend_Form_Element_Password('retypepassword');
$retypepassword->setLabel("Retype-Password :")
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator(
'NotEmpty',
TRUE,
array('messages' => array(
'isEmpty' => 'Please enter confirm password.'
)
)
)
->addValidator(
new Zend_Validate_Identical('newpassword'),
TRUE,
array('messages' => array(
'notSame' => 'New password and confirm password are not matching. They must be same.',
'missingToken' => 'New password and confirm password are not matching. They must be same.'
)
)
)
->addValidator('StringLength', false, array(4, 25))
->getValidator('StringLength')->setMessage("Should be 4-25 characters long.");
As you can see that I had override the error messages for Zend_Validate_Identical i.e. for notSame and missignToken, but still the form is showing the default error message i.e. "The two given tokens do not match"
Can anyone please help me.
Thanks In Advance...
The $options parameter to Zend_Form_Element::addValidator gets ignored completely if you pass it a validator object (which you're doing by passing new Zend_Validate_Identical).
Instead, you want to do something closer to the way you've added your other validators:
$this->addValidator(
'Identical',
TRUE,
array('token' => 'newpassword',
'messages' => array(
'notSame' => 'New password and confirm password are not matching. They must be same.',
'missingToken' => 'New password and confirm password are not matching. They must be same.'
)
)
);