Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have got two fields namely number and percentage. I want a user to input value in only one input field. If a user inputs values in both number and percentage field, the system should throw validation error. Is there anything we can do with laravel validation to achieve this?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can write a custom validator for that: http://laravel.com/docs/5.0/validation#custom-validation-rules

It may looks somthing like this:

class CustomValidator extends IlluminateValidationValidator {

    public function validateEmpty($attribute, $value)
    {
        return ! $this->validateRequired($attribute, $value);
    }

    public function validateEmptyIf($attribute, $value, $parameters)
    {
        $key = $parameters[0];

        if ($this->validateRequired($key, $this->getValue($key))) {
            return $this->validateEmpty($attribute, $value);
        }

        return true;
    }
}

Register it in a service provider:

Validator::resolver(function($translator, $data, $rules, $messages, $attributes)
{
    return new CustomValidator($translator, $data, $rules, $messages, $attributes);
});

Use it (in a form request, for example):

class StoreSomethingRequest extends FormRequest {
    // ...

    public function rules()
    {
        return [
            'percentage' => 'empty_if:number',
            'number'     => 'empty_if:percentage',
        ];
    }
}

Update Just tested it in Tinker:

Validator::make(['foo' => 'foo', 'bar' => 'bar'], ['bar' => 'empty_if:foo'])->fails()
=> true
Validator::make(['foo' => '', 'bar' => 'bar'], ['bar' => 'empty_if:foo'])->fails()
=> false
Validator::make(['foo' => '', 'bar' => 'bar'], ['foo' => 'empty_if:bar'])->fails()
=> false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...