I'm having a small issue with my Laravel rules and regex operation :
Basically a rule is an array as such :
'room'=>'required|alpha_num|min:2|max:10',
The problem i'm having is when using regex and the | (or) operator such as :
'cid'=>'required|regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i',
I'm getting a server error saying :
ErrorException
preg_match(): No ending delimiter '/' found
I'm guessing the preg_match is stopping at the first | inside the /.../.
Is there anyway to write the above code to make it work ?
Full code :
public static $rules = array(
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i'),
'description'=>'required|regex:/^[A-Za-z \t]*$/i|min:3|unique:courses',
'credits'=>'required|regex:/^\d+(\.\d)?$/'
);
http://laravel.com/docs/validation#rule-regex
regex:pattern
The field under validation must match the given regular expression.
Note: When using the regex pattern, it may be necessary to specify rules in an array instead >of using pipe delimiters, especially if the regular expression contains a pipe character.
To clarify:
You would do something like this
$rules = array('test' => array('size:5', 'regex:foo'));
You should use an array instead of separating rules using |:
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i')
The pipe (|) sigh is available in your regular expression pattern so it's conflicting with the separator. Other answer already stated it.
I use this style and save my life :-)
change code from
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => 'required|integer|between:0,1000000|regex:/[1-9][0-9]*0000$/'
]
]);
to
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => [ // <=== Convert To Array
'required',
'integer',
'between:0,1000000',
'regex:/([1-9][0-9]*0000$)|([0])/' // <=== Use pipe | in regex
] // <=== End Array
]);
Related
I'm trying to do alphanumeric with spaces validation in CakePHP 3.5.13.
So I've added the following to one of my Table classes:
// src/Model/Table/SavedSearchesTable.php
public function validationDefault(Validator $validator)
{
$validator->add('search_name', [
'alphanumeric' => [
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]);
return $validator;
}
This does exactly what I want - I get a validation error message if I enter a string that contains characters other than A-Z, 0-9 or a space.
However...reading about Using Custom Validation Rules in the documentation all of the ->add() calls use 3 parameters.
I've looked into the source (vendor/cakephp/cakephp/src/Validation/Validator.php) and the method looks like this:
public function add($field, $name, $rule = [])
{
// ...
}
How can my rule work if I've passed an array for the second parameter, which it's treating as $name?
Edit : Someone has mentioned in the comments that there is a fallback for older code. Well, if I try and use 3 parameters (instead of 2) in the Model (note addition of 'custom' as second param):
$validator->add('search_name', 'custom', [
'alphanumeric' => [
'rule' => ['custom', '/^[a-z0-9\' ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]);
It now produces an error:
Unable to call method "" in "default" provider for field "search_name"
The correct answer to this was provided by #ndm in the comments.
I'm writing out a full example in case anyone else has this problem.
It can either be written as:
$validator->add(
'search_name',
'alphanumeric',
[
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
);
or:
$validator->add('search_name',
[ // second argument is an array. This was how it was in the original question.
'alphanumeric' =>
[
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]
);
The following is given as a comment in Cake's source code regarding how the add() method works:
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
Both of these have been tested and give the same result in CakePHP 3.5.13
I am trying to make a regex for price OR empty.
I have the price part (Dutch uses comma instead of point) which actualy works
/^\d+(,\d{1,2})?$/
The regex above validates ok on the value 21,99
Now I try to add the empty part so the field can be... just empty ^$
/(^$|^\d+(,\d{1,2})?$)/
But Laravel starts to complain as soon as I change the regex:
"Method [validate^\d+(,\d{1,2})?$)/] does not exist."
Works ok:
$rules = [
'price' => 'regex:/^\d+(,\d{1,2})?$/'
];
Laravel says no...:
$rules = [
'price' => 'regex:/(^$|^\d+(,\d{1,2})?$)/'
];
Kenken9990 answer - Laravel doesn't break anymore but an empty value is still wrong:
$rules = [
'price' => 'regex:/^(\d+(,\d{1,2})?)?$/'
];
is this work ?
$rules = [
'price' => 'nullable|regex:/^(\d+(,\d{1,2})?)?$/'
];
| is also the separator for multiple validation rules.
For example the following is valid:
$rules = [ "price" => "nullable|numeric|between:0,99" ];
To use it regex you need to switch to using an array:
$rules = [
'price' => [ 'regex:/(^$|^\d+(,\d{1,2})?$)/' ]
];
This is also pointed out in the documentation:
Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
Incidentally the original rule might also do what you want and can also be written as:
$rules [
'price' => [ 'nullable', 'numeric', 'between:0,99' ]
]
I have created a a registration form where a farmer will input his name. The name may contain hyphen or white spaces. The validation rules are written in the app/http/requests/farmerRequest.php file:
public function rules()
{
return [
'name' => 'required|alpha',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
But the problem is the name field is not allowing any white spaces because of the alpha rule. The name field is varchar(255) collation utf8_unicode_ci.
What should I do, so that user can input his name with white spaces?
You can use a Regular Expression Rule that only allows letters, hyphens and spaces explicitly:
public function rules()
{
return [
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
You can create a custom validation rule for this since this is a pretty common rule that you might want to use on other part of your app (or maybe on your next project).
on your app/Providers/AppServiceProvider.php
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//Add this custom validation rule.
Validator::extend('alpha_spaces', function ($attribute, $value) {
// This will only accept alpha and spaces.
// If you want to accept hyphens use: /^[\pL\s-]+$/u.
return preg_match('/^[\pL\s]+$/u', $value);
});
}
Define your custom validation message in resources/lang/en/validation.php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
// Custom Validation message.
'alpha_spaces' => 'The :attribute may only contain letters and spaces.',
'accepted' => 'The :attribute must be accepted.',
....
and use it as usual
public function rules()
{
return [
'name' => 'required|alpha_spaces',
'email' => 'email|unique:users,email',
'password' => 'required',
'phone' => 'required|numeric',
'address' => 'required|min:5',
];
}
You can use This Regular Expression to validate your input request. But, you should carefully to write RegEx rules to implement.
Here, you can use this Regex to validate only alphabet & space are allowed.
public function rules()
{
return [
'name' => ['required', 'regex:/^[a-zA-Z\s]*$/']
];
}
I know, this answer may little bit changes with others. But, here is why I make some changes :
Using array in rules. As mention in Laravel Docs, you should better using array as rules when using Regex.
Using specified Regex for validate input request. Of course, you can selected answer above, but I recently found some bug with it. It allow Empty Characters to pass validation. I know, this might little bit paranoia, but if I found the better answer, why not using it?.
Don't get me wrong. I know, other answer is good. But I think it's better to validate everything as specific as we needed, so we can secure our app.
Problem
I am trying to validate a form using the Laravel built in validation. I want to make sure that the email only has a .edu in it. However, there Laravel continues to throw a preg_match(): No ending delimiter '/' found error. I heard this has something to do with a pipe delimiter instead of an array one, but I am unsure what this mean / how to fix it. The code I have is below.
$validator = Validator::make(Input::all(),
array(
'email' => 'Required|Max:50|Email|Unique:users|Regex:/(\.edu(\.[a-z]+)?|\.ac\.[a-z]+)$/',
'first-name' => 'required|max:20|min:3|',
'last-name' => 'required|max:30|min:3|',
'username' => 'required|max:30|min:3|unique:users|',
'city' => '',
'state' => '',
'password-init' => 'required|min:6|AlphaNum',
'password-check', 'required|min:6|AlphaNum|same:password-init'
)
);
Any help would be appreciated
Thanks!
Since you're using pipes | to separate your different validation rules, Laravel gets confused when it sees a pipe in the middle of your Regex. So break up just the "email" rule like this:
$validator = Validator::make(Input::all(),
array(
'email' => array(
'required',
'max:50',
'email',
'unique:users',
'regex:/(\.edu(\.[a-z]+)?|\.ac\.[a-z]+)$/'
),
'first-name' => 'required|max:20|min:3|',
...
That's what it means when it talks about an array instead of pipes in the doc:
http://laravel.com/docs/4.2/validation#rule-regex
I'm having a small issue with my Laravel rules and regex operation :
Basically a rule is an array as such :
'room'=>'required|alpha_num|min:2|max:10',
The problem i'm having is when using regex and the | (or) operator such as :
'cid'=>'required|regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i',
I'm getting a server error saying :
ErrorException
preg_match(): No ending delimiter '/' found
I'm guessing the preg_match is stopping at the first | inside the /.../.
Is there anyway to write the above code to make it work ?
Full code :
public static $rules = array(
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i'),
'description'=>'required|regex:/^[A-Za-z \t]*$/i|min:3|unique:courses',
'credits'=>'required|regex:/^\d+(\.\d)?$/'
);
http://laravel.com/docs/validation#rule-regex
regex:pattern
The field under validation must match the given regular expression.
Note: When using the regex pattern, it may be necessary to specify rules in an array instead >of using pipe delimiters, especially if the regular expression contains a pipe character.
To clarify:
You would do something like this
$rules = array('test' => array('size:5', 'regex:foo'));
You should use an array instead of separating rules using |:
'cid' => array('required', 'regex:/^((comp)|(soen)|(engr)|(elec))\d{3}$/i')
The pipe (|) sigh is available in your regular expression pattern so it's conflicting with the separator. Other answer already stated it.
I use this style and save my life :-)
change code from
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => 'required|integer|between:0,1000000|regex:/[1-9][0-9]*0000$/'
]
]);
to
$validator = Validator::make(
$request->all(),
[
'name' => 'required|string',
'initial_credit' => [ // <=== Convert To Array
'required',
'integer',
'between:0,1000000',
'regex:/([1-9][0-9]*0000$)|([0])/' // <=== Use pipe | in regex
] // <=== End Array
]);