Refine will be launching soon 🎉 Sign up for the early access list to stay up to date.
Refine for Laravel
A package by Hammerstone

Validating User Input

Hammerstone Refine has not launched yet. Sign up for the early access list to stay up to date!

In most cases, your frontend UI will be built based on data from the backend, but it's still important that we validate user input and present validation errors if necessary.

Automatic Validation

There are several common cases where we handle validation automatically for you, without any extra work on your part.

Clauses

Every condition that uses clauses will validate that the user has selected one of the clauses allowed by the developer.

OptionCondition

The OptionCondition will validate that the user has chosen one of the allowed values.

DeferredOptionCondition

The DeferredOptionCondition will also validate that the user has chosen one of the allowed values.

DateCondition

The DateCondition will automatically validate that the inputs passed to it are of the appropriate type. If two dates are required, it will ensure that two dates are present.

If your user chooses a relative clause, the DateCondition will validate that the first input is a number and the second input is a direction ("ago" or "from now").

Custom Validation

We handle a lot of the validation for you, but should you find yourself needing to validate something additional, there is an addRules method you can use.

In fact, all of the standard conditions use the addRules method to apply their own rules. Take a look at this example from the HasClauses trait:

1protected function bootHasClauses()
2{
3 $this->addRules([
4 'clause' => [
5 'required',
6 function () {
7 return Rule::in(Arr::pluck($this->getClauses(), 'id'));
8 }
9 ]
10 ]);
11}

This adds two rules to the clause attribute. The first is that the clause is required. The second is that the clauses must be one of the clauses that the developer has allowed.

Note that you can pass in a closure to be lazily evaluated at validation-time. This allows you to use the fluent methods to build up the perfect condition and the validation to take that into account.

If you wanted to add custom validation to a condition, you could do so in the boot method:

1// In your custom condition...
2 
3public function boot()
4{
5 parent::boot();
6 
7 $this->addRules([
8 // Any Laravel validation rules.
9 ], [
10 // Custom messages for your custom rules.
11 ]);
12}
Code highlighting powered by torchlight.dev, a Hammerstone product.

If the validation passes, nothing happens. If validation fails, a ValidationException is thrown with the appropriate messages. That exception is caught further up the stack and formatted in the appropriate way for the frontend to consume.