0

I'm implementing a form with dynamic fields being added by an add field button. What I need is to prevent some of these fields to have the same value before submission.

Currently my Request rules look like this:

public function rules()
{
    return [
        'myfield.*.domain' => 'required|url',
        'myfield.*.group' => 'required',
        'myfield.*.client' => 'nullable'
    ];
}

For instance, what if want the domain input to be unique in the form submission (not the database)? Is this possible?

Any help would be really appreciated!

Thanks!

EDIT

Adding 'distinct' rule did the job for the specific field.

'myfield.*.domain' => 'required|url|distinct'

The validation errors though sometimes don't show up at my view. Testing the same input errors on purpose, the error messages sometimes show up as they should and sometimes $errors->all() returns an empty array.

@foreach ($errors->all() as $error)
    <div class="card-panel red white-text alert">
        <span>{{ $error }}</span>
    </div>
@endforeach 
  • Its doable but not fail proof, you'll need to use javascript to do the client side validation. A user can always disable js entirely or manipulate the dom via the web inspector. – Brian Lee Jun 29 '18 at 10:16
  • Thanks @DigitalDrifter I use frontend validation but I want to implement backend validation too to make it more strict and safe – James Blackmore Jun 29 '18 at 12:28

1 Answers1

0

You have two ways to achieve what you ask:

First, and more easy, use an after validation on your form request:

public function withValidator($validator){
  $validator->after(function ($validator) {
     $domain = $this->domain;
     if($this->group == $domain || $this->client == $domain){
        $validator->errors()->add('Domain', 'Domain must be unique in form');
     }
  }
}

Second and more reusable way is to create your own custom rule, here is the official docs to do that.

JoseSilva
  • 517
  • 5
  • 29