2

I am trying to validate a form request and I want to accept the field say test if only it has a value or ABC or XYZ. How can I achieve this?

I currently have

$request->validate([
    'test' =>  'required|unique:tests',   
]);
2
  • See, there is no need to validation required. You can use like: if(!empty($request->test) || $request->test == 'ABC' || $request->test == 'XYZ') { Do the things here} Hope this helps you! Let me know. Nov 23, 2017 at 5:41
  • And if you want to use only laravel validation rule, use regex like: $request->validate([ 'test' => 'required|unique:tests|regex:/ABC|XYZ/g', ]); Here g is global search , retain the index of last match Nov 23, 2017 at 5:52

2 Answers 2

12

The Laravel docs are quite helpful when it comes to these issues.

Laravel Docs - Validation - Available Methods

Laravel Docs - Validation - Rule - in

'test' => [
    'required',
    Rule::in(['ABC', 'XYZ']),
]

or

'test' => 'required|in:ABC,XYZ',
1
  • 1
    There was no need for the condescension. You could have just said, "There is a [in] rule which would handle this situation." The [in] rule is easily overlooked if the programmer is searching for a way to OR rules. Apr 17, 2022 at 10:47
2

You can use regular expression to validate this field

your regular expression for ABC OR XYZ

Code is

 $request->validate([
    'test' =>  'required|unique:tests|regex:/ABC|XYZ/g',   
]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.