3
votes

I have 2 field say var1 and var2. both are text fields what I want if var2 contains a word __tocken_ then field var1 is required.

I tried this but it is not working,

$validator = Validator::make(
    ['var1' => 'required_if:var2,regex:/__tocken_/']
    //['var2' => ['required', 'regex:/__tocken_/']] //<--Regex is working fine here
);

So what I'm doing right now I'm setting a 3rd variable var3 and on form submit I'm doing a JS validation if var2 contains a word with pattern __tocken_ then I'm setting var3 as 1 otherwise 0. And the validation rule is

$validator = Validator::make(
    ['var1' => 'required_if:var3,1'] //working fine
);

So my question is it possible to have regex NOT the exact value in required_if validation rule?

Sample possible value for var2

  • Hi __FIRST_NAME__, lorem ispam __tocken_Ur1vG6xK__.
  • lorem ispam __tocken_456vG6xK__ lorem __tocken_T57kq6xK__
  • lorem ispam.. so on
1
perhaps you're in need of custom validatorBagus Tesa
@BagusTesa: Yes I can do it with custom validation, but I was looking for more inbuilt method.Raunak Gupta
I think you should work on validation rules for var2 as such: ['var2' => 'sometimes|regex:/__tocken_/|required_with:var1']revo
thanks @revo; for your suggestion, var2 is fully optional, only if it has a above mention pattern then var1 is needed. So I was adding validations to var1. Moreover I cannot able to make your suggestion to working.Raunak Gupta
Since it would be optional you have to use sometimes rule. If it has a value then it should contain __tocken_ to make var1 a required field as well.revo

1 Answers

0
votes

Check it out:

$validator->sometimes('var2', 'required', function ($input) {
    return (bool) preg_match('/__tocken_/', $input->var1);
});