简体   繁体   中英

Laravel - both input values can't be no how to validate?

I'm using Laravel for a project and want to know how to validate a particular scenario I'm facing. I would like to do this with the native features of Laravel if this is possible?

I have a form which has two questions (as dropdowns), for which both the answer can either be yes or no, however it should throw a validation error if both of the dropdowns equal to no, but they can both be yes.

I've check the laravel documentation, but was unsure what rule to apply here, if there is one at all that can be used? Would I need to write my own rule in this case?

very simple:

let's say both the fields names are foo and bar respectively.

then:

 // Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc

 // if validation passes, add this (i.e. inside if($validator->passes()))

 if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
 {
     $messages = new Illuminate\Support\MessageBag;
     $messages->add('customError', 'both fields can not be no');
     return Redirect::route('route.name')->withErrors($validator);
 }

the error messge will appear while retrieving.

if you get confuse, just dump the $error var and check how to retrieve it. even if validation passes but it gets failed in the above code, it won't be any difference than what would have happened if indeed validation failed.

Obviously don't know what your form fields are called, but this should work.

This is using the sometimes() method to add a conditional query, where the field value should not be no if the corresponding field equals no.

    $data = array(
        'field1' => 'no',
        'field2' => 'no'
    );

    $validator = Validator::make($data, array());
    $validator->sometimes('field1', 'not_in:no', function($input) {
        return $input->field2 == 'no';
    });
    $validator->sometimes('field2', 'not_in:no', function($input) {
        return $input->field1 == 'no';
    });

    if ($validator->fails()) {
        // will fail in this instance
        // changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
    } 

Just to note, this will only work in Laravel 4.2+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM