Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nabilunfarhanun's avatar

Best practice for validation and dry principle

What I read from the internet is it is good practice to validate both in front end and back end. Front end validation is needed for user friendliness. And back end validation is needed for security.

However how can I follow the dry principle while doing validation in both end?

For example, suppose, I have a form where it will accept password. And the password minimum length is 6. I did the back end validation with form controller and the front end validation with javascript.

However, if somehow the minimum length is changed to 8 then I need to change the length in two places. One is in back end; another in front end. Isn't it violating the dry principle? How can I manage this in such a way that I would need to change in only one place? What is the best practice in this case?

0 likes
3 replies
Dunsti's avatar
Dunsti
Best Answer
Level 6

One way could be, to create the JavaScript validation rules on the backend.

put the rules in a placeholder and fill it while rendering the view:

something like this in your template:

<script>{{ $rules }}</script>

something like this in your controller

return view('myform', ['rules' => ' ... ']);

The format of the rules depends on your implementation, but could be some JSON, or similar.

MThomas's avatar

you could also use a FormRequest object. And validate the field in an asynchronous API call to the server. In this way you will have the exact same rules 'client side'.

1 like
kobear's avatar

Check this out. Looks like it would do what you want:

https://github.com/proengsoft/laravel-jsvalidation

  • Automatic creation of Javascript validation based on your Validation Rules or FormRequest, no Javascript coding required.
  • Supports other validation packages.
  • AJAX validation for ActiveURL, Unique and Exists Rules, Custom Validation Rules and other validation packages
  • Unobtrusive integration, you can use without Laravel Form Builder
  • The package uses Jquery Validation Plugin bundled in provided script.
  • Uses Laravel Localization to translate messages.

Please or to participate in this conversation.