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

arielenter's avatar

Transform validation rules into inputs with their attributes

Given I have the following validation rules:

array:2 [▼
  "username" => array:6 [▼
    0 => "required"
    1 => "string"
    2 => "min:3"
    3 => "max:64"
    4 => "regex:/^[a-z]([a-z0-9]|[a-z0-9]\.[a-z0-9])*$/i"
    5 => "unique:App\Models\User"
  ]
  "password" => array:4 [▼
    0 => "required"
    1 => "string"
    2 => "confirmed"
    3 => Illuminate\Validation\Rules\Password {#295 ▶}
  ]
]

I was thinking I could make a function that will transform it into this:

array:2 [▼
  "username" => array:6 [▼
    "name" => "username"
    0 => "required"
    "type" => "text"
    "min" => "3"
    "max" => "64"
    "pattern" => "^[a-z]([a-z0-9]|[a-z0-9]\.[a-z0-9])*$"
  ]
  "password" => array:4 [▼
    "name" => "password"
    0 => "required"
    "type" => "password"
    "min" => 6
  ]
]

Witch can be use to construct my form in the view. This way, if I ever add a new field or change a validation parameter I only change it in one place at the request validation.

Does something like this already exist? If not, would it be some how useful or am I just trying to reinvent the wheel? The way I’m doing it right now is that I pass the validation rules to the view, and later I use the helper function in the view.

I’m attaching, the helper.php I made. Of course, it would be a work in process so that it can check for other input types and attributes. Could some one teach me how could I go about refactoring it? Thank you.

0 likes
2 replies

Please or to participate in this conversation.