I have a little problem in laravel validation request. I want to reject username with space like foo bar. I just want to allow foobar without space. Right now my rule is required|unique:user_detail,username. What rule should i use? thanks
Why don't you use alpha_dash rule?
required|alpha_dash|unique:user_detail,username
From the documentation:
The field under validation may have alpha-numeric characters, as well
as dashes and underscores.
And it doesn't allow spaces.
You can extend the validator with your own custom rules:
Validator::extend('without_spaces', function($attr, $value){
return preg_match('/^\S*$/u', $value);
});
Then just use as any other rule:
required|without_spaces|unique:user_detail,username
Checkout the docs on custom validation rules:
https://laravel.com/docs/5.2/validation#custom-validation-rules
You should use regular expression with your validation.
PHP :
required|unique:user_detail,username,'regex:/\s/'
Laravel validation for username or subdomain
"subdomain" => [
"regex:/^[a-zA-Z0-9]+$/",
"required", "min:3","max:20","unique:subdomains",
],
You should use regular expressions with your validation.
Laravel:
'domain' => 'required|max:255|unique:users|regex:/(^[a-zA-Z]+[a-zA-Z0-9\\-]*$)/u',
The assumption is that a username can contain either (only alphabetic letters) or a mixture of (alphabetic letters and numbers).
In that case, the rules below should work.
(for alphabetic letters) -> ['username' => 'alpha'] //eg johndoe
(for alphabetic letters and numbers) -> ['username' => 'alpha_num'] //eg johndoe123
Related
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:
How to add line break in laravel language files?
I have tried to use ,, \n\r,
to break line and add new line but all these not work.
return [
'best_hospitality' => 'Simply <br /> the best hospitality',
];
You can use
'best_hospitality' => "<pre>Simply\r\nthe best hospitality</pre>",
or 'best_hospitality' => sprintf ('<pre>Simply%sthe best hospitality</pre>',PHP_EOL ),
please note the use of double quotes in the first example, it is not working with single quotes if you use the \r\n inside the string, this is why
if you try echo(Lang::get('message.best_hospitality')) you will see the new line:
I am not so sure if you need the pre tag, depends where you need to use the Lang for html or not, eg using (double quotes here):
'best_hospitality' => "Simply\r\nthe best hospitality",
and var_dump(Lang::get('message.best_hospitality')); exit;
has the output
C:\wamp64\www\test\app\Http\Controllers\TestController.php:24:string 'Simply
the best hospitality' (length=39)
Does this cover your case?
You need HTML Entity Names on your lang files.
Try this :
return [
'best_hospitality' => 'Simply <br> the best hospitality',
];
May I suggest creating a custom helper function for this specific case?
Add this into your helpers.php file:
if (! function_exists('trans_multiline')) {
/**
* Retrieve an escaped translated multiline string with <br> instead of newline characters.
*/
function trans_multiline($key, array $replace = [], string $locale = null): string
{
return nl2br(e(__($key, $replace, $locale)));
}
}
Now you will have a function trans_multiline() available for you in any view, which will behave pretty much like the built-in __() helper.
The function will fetch a localized string of text and replace any newline \r\n symbol with <br> tag.
Caveat: For a proper escaping it must be done before nl2br() function, like you see in the code above. So, to prevent any weird errors due to double-escaping, you must use this custom helper without any additional escaping, like so:
{!! trans_multiline('misc.warning', ['name' => 'Joe']) !!}
Escaping will be handled by the e() function (which is what Laravel uses under the hood of {{ }}) inside the helper itself.
And here's how you define a multiline translation string:
'warning' => "There's only 1 apple, :name!\r\nDon't eat it!"
Make sure to use double-quotes, so PHP actually replaces \r\n with a newline character.
Obviously, parameter replacing still works exactly like with the __() helper.
is there a way in Laravel 5 to have a recognized list of prefixes, such as ['gbr','en','eu'], so that
/gbr/bar/baz/shoelace // or
/eu/bar/baz/shoelace
is handled by the same controller#method as
/bar/baz/shoelace
Except that the additional parameter foo=gbr is passed in the first condition?
Note the Route::group prefix won't work because there may or may not be a prefix in this case. Also, this strategy should take precedence over all else, i.e. the Route would check for the (optional) prefix first.
Yes there is a way.
When declaring your routes, you can declare them as
Route::get('{prefix}/bar/baz/shoelace', 'controller#method')->where('prefix', 'gbr|en|eu');
gbr|en|eu is a simple regular expression that will match either the string gbr, en or eu. Check out Regular expression constraints for more details
And in your controller you can have
public function method($prefix) {
//code here
}
'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);
}
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;
}