Validating User Input
Refine is a paid package. To purchase, head to hammerstone.dev.
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:
protected function bootHasClauses(){ $this->addRules([ 'clause' => [ 'required', function () { return Rule::in(Arr::pluck($this->getClauses(), 'id')); } ] ]);}
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:
// In your custom condition... public function boot(){ parent::boot(); $this->addRules([ // Any Laravel validation rules. ], [ // Custom messages for your custom rules. ]);}
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.