skip to Main Content

I want to give a validation rule for card information:

  • required when number_of_guests field value is greater than or equal to 15
  • card_information will be required when number_of_guests field value is greater than or equal to 15
$rules = [
    'number_of_guests' => 'numeric|required|max:100',
    'card_information' => 'required_if:number_of_guests,>=15'
];

3

Answers


  1. The required_if rule needs a slight adjustment to work with numerical values. You can use the integer rule instead of numeric for the number_of_guests field to ensure it’s an integer, and then use required_if with the appropriate condition.

    $rules = [
    'number_of_guests' => 'integer|required|max:100',
    'card_information' => 'required_if:number_of_guests,>=15'
    ];
    $request->validate($rules);
    
    Login or Signup to reply.
  2. I’d use something like

    $rules = [
        ...
    ];
    if (number_of_guests >= 15) {
        // Add additional rules to $rules
    }
    // do validation
    
    Login or Signup to reply.
  3. $rules = [
        'number_of_guests' => 'numeric|required|max:100',
        'card_information' => 'required_if:number_of_guests,>=,15' // Corrected syntax
    ];
    

    The key change is in the card_information rule. The correct syntax for the required_if rule is:

    'field_name' => 'required_if:other_field_name,operator,value'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search