I'm not great with RegEx and wondering if someone could help explain how I can go about not allowing the following. I want to block the user from being able to enter any emojis in a string as well as only punctuation. i.e.
".." => fail
"-----" => fail
",,,," => fail
"Mc-Donald" => pass
Any emojis in the string should also result in a fail.
I was thinking of setting up a custom Laravel rule for this using regex to check if the string contains only punctuation or any emojis.
Perhaps a better way might be for a RegEx to only allow certain characters? As I only really want to allow only letters, numbers and punctuation (just not only puncation on it's own)
Thanks for any help!
CodePudding user response:
Check out the validation rule alpha_dash
https://laravel.com/docs/9.x/validation#rule-alpha-dash or alpha_num
. If you want to finetune it, you can use the following code to customize your own regex:
(Add this to a service provider)
Validator::extend('alpha_num_dash', function($attribute, $value) {
if(!is_string($value) && !is_numeric($value)) {
return false;
}
return preg_match('/^[a-zA-Z0-9\-] $/', $value);
});
I will not explain the regex meaning here since it is out of scope. Look up a guide and you will quickly learn the ropes of that. Furthermore, you could try an online service like https://regex101.com/r/PxtN3U/1 to tinker with the regex.
CodePudding user response:
There is a php function ctype_punct that "check for any printable character which is not whitespace or an alphanumeric character".
Something like that:
$validator = Validator::make($request->all(), [
'title' => [
'required',
'max:255',
function ($attribute, $value, $fail) {
if (ctype_punct($value)) {
$fail('The '.$attribute.' is invalid.');
}
},
],
]);
More detailed validation will require regex, e.g. must contains at least one "alphabetical character":
$validator = Validator::make($request->all(), [
'title' => ['required','max:255','regex:/[a-zA-Z]/'],
]);