CakePHP validation errors - validation

I'm trying to validate an input with CakePHP 2.3.8. When the input passes the validation it works fine. However, when it doesn't meet the validation requirements I get the following error
Warning (2): vsprintf(): Too few arguments [CORE/Cake/basics.php, line 619]
This displays at the top. Around the input where the message should be displayed, it's just a blank red outline, like the message wasn't passed.
Here's my validation
'sales_tax' => array(
'valid' => array(
'rule' => array('confirm_percentage'),
'message' => 'Sales tax must be a percentage (Ex: 4.005%)'
)
),
I also tried this without the 'valid' array and the error still persists. And the function
function confirm_percentage($value){
if(preg_match('/^[0-9]/', $value['sales_tax'])){ //just checking if input starts with number for testing purposes
return true; //no error
}
}

Ultimately your validation rule message is being passed to vsprintf() (in __d()), and so it must be formatted to be sprintf compatible.
The problem is that you are passing an %, which is the conversion specifier identificator, and so vsprintf() expects you to pass additional arguments appropriately.
Long story short, escape the % with another %:
'message' => 'Sales tax must be a percentage (Ex: 4.005%%)'

Related

Laravel Validator "in:" not seeing first element

I have the following ruleset. The "in:" rules will fail with not found if the first element in the array is entered in the input field. However if 2nd or subsequent elements are selected then the rule fires ok. Has anyone else had this issue? I am using "Laravel 7"
"title": "required|min:2|max:50|regex:/^[a-zA-Z][a-zA-Z ]+$/u",
"target_start_date": "required|date_format:Y-m-d|after_or_equal:today",
"target_finish_date": "required|date_format:Y-m-d|after_or_equal:target_start_date",
"genre": "required|in:[adventure,action,biographical,contemporary,crime,thriller,mystery,fantasy,historical,horror,medical,myths,political,romance,sci_fi,war]",
"visibility": "required|in:[public,friends,public]",
"owner_starts": "required|in:[yes,no,sequence,random]",
"owner_finishes": "required|in:[yes,no,sequence,random]"
That’s not how you specify values for the in rule; you just specify the options as comma-delimited strings. For example:
'visibility' => ['required', 'in:public,friends'],
(I’ve also used the “array” syntax for specifying rules, as it makes each individual validation rule easier to see rather than a long string full of | characters.)
If the available options are stored as an array elsewhere in your application, such as a repository or a configuration file, then you can pass that array of options directly to the “fluent” rule builder as per Charlie’s answer:
'genre' => [
'required',
Rule::in($genres),
],
Be sure to import Illuminate\Validation\Rule if you want to use this approach.
"owner_finishes": "required|in:[yes,no,sequence,random]"
Should be:
use Illuminate\Validation\Rule;
'owner_finishes' => [
'required',
Rule::in(['yes', 'no', 'sequence', 'random']),
],
As the docs says:
Since this rule often requires you to implode an array, the Rule::in method may be used to fluently construct the rule:

required_without not working with other rules

'person.mail' =>'required_without:person.phone|sometimes|email|unique:persons,mail',
'person.phone' => 'required_without:person.mail|sometimes|regex:/[0-9]/|size:10|unique:persons,phone'
i need to validate phone and mail, one of them is mandatory
when the mail is empty and the phone isn't, the validation fails at the email rule and this goes both ways, when the mail is present and phone empty, it fails at the regex rule
how can i stop validation if value is null?
As the laravel docs state:
In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list.
I get the feeling that you actually do post both person[email] and person[phone], in which case sometimes will instruct validation to continue, since the values will then be empty strings (or maybe null) rather than not present. You can conditionally add rules on other assertions than check whether key x exists by creating your own validator, and use its sometimes() method to create your own assertions:
$v = Validator::make($data, [
'person.email' => 'email|unique:persons,mail',
'person.phone' => 'regex:/[0-9]/|size:10|unique:persons,phone',
]);
$v->sometimes('person.email', 'required', function($input) {
return ! $input->get('person.phone');
});
$v->sometimes('person.phone', 'required', function($input) {
return ! $input->get('person.email');
});
The difference here is that the fields are not by default required. So for example, person.phone may either be empty, or must match your regex. If $input->get('person.email') returns a falsy value, person.phone is required after all.
As a note, I think your regex is wrong. It will pass as soon as any character inside person.phone is a number. I think you're looking for something like this:
'person.phone' => 'regex:/^[0-9]{10}$/|unique:persons,phone'
i worked it around like this, it's not the best way, but it works just fine
after the validation i added
if(empty($request->all()['person']['mail']) && empty($request->all()['person']['phone'])){
$validator->errors()->add('person.mail', 'Mail or phone required');
$validator->errors()->add('person.phone', 'Mail or phone required');
return redirect("admin/people-create")->withInput()->withErrors($validator);
}

SugarCRM 6.5 CE: how to customize label in editview using Smarty

I'm trying to customize a label in an edit view using Smarty.
A field named decription should have label LBL_LABEL_ONE with a currency symbol if some_fieds has value 1, LBL_LABEL_TWO otherwise.
With the following code in detailviewdefs.php, I have no problems to accomplish this in the view detail:
array (
'name' => 'description',
'label' => '
{if $bean->some_field==1}
{$MOD.LBL_LABEL_ONE} {$CURRENCY}
{else}
{$MOD.LBL_LABEL_TWO}
{/if}',
),
Note that some_field is a field of the current module and $CURRENCY is assigned in view.detail.php with the following code:
function preDisplay() {
parent::preDisplay();
$currency = new Currency();
$this->ss->assign('CURRENCY', $currency->getDefaultCurrencySymbol());
}
Using same code in editviewdefs.php I have several problems:
First: the following fatal error getting the field of the bean:
Fatal error: Smarty error: [in
cache/modules/omn_fornitura_gas/EditView.tpl line 506]: syntax error:
invalid attribute name: '$bean->some_field'
(Smarty_Compiler.class.php, line 1536) in
C:\xampp\htdocs\sugar\include\Smarty\Smarty.class.php on line 1095
Second: the variable $CURRENCY seems not to be correct:
{€' module='omn_fornitura_gas'}
instead of
€
Quite a puzzle this one.
The reason you're seeing such a thing is that Sugar seems to render Smarty Detail and Edit view definitions quite differently.
The Problem
In detail, it very neatly compiles the field as such:
cache/modules/omn_fornitura_gas/EditView.tpl
{capture name="label" assign="label"}
{if $bean->some_field==1}
{$MOD.LBL_LABEL_ONE} {$CURRENCY}
{else}
{$MOD.LBL_LABEL_TWO}
{/if}{/capture}
However, in edit, it tries to insert it as an attribute of a translated label:
cache/modules/omn_fornitura_gas/EditView.tpl
{capture name="label" assign="label"}{sugar_translate label='
{if $bean->some_field==1}
{$MOD.LBL_LABEL_ONE} {$CURRENCY}
{else}
{$MOD.LBL_LABEL_TWO}
{/if}' module='omn_fornitura_gas'}{/capture}
This explains both the issues you're seeing, as it complains about the attribute, and displays the module name in the bottom line.
So what can we do about it?
Unfortunately, as the edit/detail templates are compiled and cached by Sugar, we can't feasibly get to them directly without digging quite deeply into the Sugar code.
However, what we can do is work around it by specifying a different label, and then setting that label dynamically, just like you were doing in the metadata, but this time via PHP in view.edit.php.
Try this:
editviewdefs.php
array (
'name' => 'description',
'label' => 'LBL_CUSTOM_LABEL',
),
view.edit.php
function preDisplay() {
parent::preDisplay();
$currency = new Currency();
global $mod_strings;
if ($this->bean->some_field == "1"){
$mod_strings['LBL_CUSTOM_LABEL'] = $mod_strings['LBL_LABEL_ONE'] . " " . $currency->getDefaultCurrencySymbol();
}
else {
$mod_strings['LBL_CUSTOM_LABEL'] = $mod_strings['LBL_LABEL_TWO'];
}
}
What happened there?
$mod_strings is a global variable in sugar that holds the current module's labels. What we've done here is use that to our advantage, and conditionally set what the label should be by setting the property of this custom label when the view is generated. Appreciated that this isn't technically a solution using Smarty, but I hope my above details can help shine a light on the inability to solve this problem exactly the same as the detail view definitions within Sugar.
Let me know if that helps, or if I can provide any further information!

Validation of phone numbers containing '+' and '-' characters

In CodeIgniter, how do i validate phone numbers containing '+' and '-' symbols?
You cannot enter a number with "-" since you defined integer as the validation rule. Therefore, the validation will fail. You need to work with RegEx so that you can create more complex validation. See the topic on validations in the CI manual for more info.
Your validation rule:
$this->form_validation->set_rules('foo', 'Number', 'callback_number_validation');
Note how the keyword callback_ is used to identify CI your function for validation.
Your callback function:
//$str will be the value you want to verify
function number_validation($str) {
return preg_match("your_regex", $str) ? true: false;
}

CodeIgniter: set_message for max_length[x]

How do you set an error message for max_length and min_length rules. For instance, if I set a rule max_length[6], I'd like the error message to display
Max characters allowed: 5
I got the same problem and even though this post is old, there's no correct answer.. You just have to use the string placeholder %s in second place of your message. In the documentation (http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors) there is an example for a field not being empty:
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
There, it uses the %s placeholder for the name of the field, but if you modify the 'max_length' message putting the field name first and the length second like this:
$this->form_validation->set_message('max_length', 'The field %s max length is %s');
it will work. Is not the best solution, but that one works for me. Hope it helps
application/language/en/en_lang.php I have this:
$lang['name'] = "Name";
$lang['form_required'] = "is required.";
application/language/es/es_lang.php I have this:
$lang['name'] = "Nombre";
$lang['form_required'] = "es requiero.";
application/controllers/yourController.php I have this:
$this->form_validation->set_rules('name', $this->lang->line('name'), 'required|alpha|xss_clean');
$this->form_validation->set_message('required', '%s ' . $this->lang->line('form_required'));
I hope this help!
#Daniel is correct. Per CodeIgniter's documentation, you can override the default error message for any validation rule (such as "min_length", "max_length", etc.) like this:
$this->form_validation->set_message('validation_rule', 'Your message here');
So, in your example you could do:
$this->form_validation->set_message('max_length', 'Max characters allowed: 5');
Simply include that where your validation rules exist.
gAMBOOKa,
create a 'new' rule that also checks for max_length
$this->form_validation->set_rules('username', 'Username', 'required|_max_length[12]');
and for the method..
function _max_length($val)
{
if (strlen($this->input->post('username')) > $val)
{
$this->form_validation->set_message('_max_length', 'Max characters allowed: 5')
return FALSE;
}
return TRUE;
}
add this to your controller as a new rule and set the message like so ---^
CodeIgniter has one of the better documentations out of all the frameworks. Read the userguide on their site or the one in your CI directory.
http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors
Take a look in system/language/english/form_validation_lang.php and you'll find
$lang['max_length'] = "The %s field can not exceed %s characters in length.";
Which is easily overridden by copying it to
application/language/english/form_validation_lang.php
And changing it to the string you'd like. Do not edit the file in system/ directly, then it'll be overwritten if you upgrade CodeIgniter.
There is no need to add a new method. You may set a custom message to a form validation error by accessing the "max_length" rule as shown below.
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]', array('required' => 'Username is required.','max_length' => 'Max characters allowed: 5')
);
Note: This is also applicable for "min_length" rule.

Resources