Dynamic form fields should not have same value in Laravel


Dynamic form fields should not have same value in Laravel



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.


$errors->all()


@foreach ($errors->all() as $error)


{{ $error }}

@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.
– DigitalDrifter
Jun 29 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 at 12:28





1 Answer
1



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.





Thanks @JoseSilva, adding 'distinct' rule was enough for the validation to work. I edited my thread with the new rule.
– James Blackmore
Jun 29 at 12:32






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift