I need to validate a string whose length is exactly 6 OR 8. How could I make the rule for this validation?
The number must be 6 OR 8, it cannot be between 6 and 8.
CodePudding user response:
You need to create a custom rule.
In the sample below, I used the Closure to create a custom rule, but you can create a rule object to reuse it.
I used the mb_strlen
instead of strlen
to cover multibyte. (UTF8 chars)
use Illuminate\Support\Facades\Validator;
use \Illuminate\Http\Request;
Route::get('/test', function (Request $request) {
$validator = Validator::make($request->all(), [
'title' => [
'required',
function ($attribute, $value, $fail) {
if (!(mb_strlen($value) == 8 || mb_strlen($value) == 6))
{
$fail('The ' . $attribute . ' is invalid.');
}
},
],
]);
dd($validator->errors());
});
CodePudding user response:
Try saving string length first and then check with if conditions.
$str = “hellowld”;
$len = strlen($str);
If($len == 6 || $len == 8)
//do something
Else
//throw error
or use regex validation rule for length as:
/^[68] $/
For string length.