required_without not working with other rules - laravel

'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);
}

Related

Fluent validation: either have both fields with value or both must be empty

I am trying to use fluent validation to validate the following rule:
Rule: Either both LocationLattitude and LocationLongitude must contain
a value or they must both be empty. You cannot have one field with
value and the other empty.
Can someone help me out with this?
This is the code I have written:
RuleFor(ar => ar.LocationLattitude)
.CasCade(CascadeMode.StopFirstFailure);
RuleFor(ar => ar.LocationLongitude)
.CasCade(CascadeMode.StopFirstFailure);

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:

CakePHP validation errors

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%%)'

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