Skip to content

BaseField Validation

tanthammar edited this page Sep 27, 2020 · 5 revisions

->errorMsg(string $string)

Add a custom error message displayed on field validation error

->realtimeValidationOff()

Wait with field validation until the form is submitted.

->errorMsg(string $message)

  • Set a custom text to be displayed instead of the default message on validation errors.
  • $message = The custom validation message.
Input::make('City')
    ->help('Please enter your current city.')
    ->errorMsg('The city does not match your current location'),

->rules($rules)

Standard Laravel validation syntax, default = 'nullable'

You do not have to add $rules=[] to the component. It is provided by the TallForms trait.

Examples

Conditional rules in field declaration

Set the validation based on if the model exists, important if using optional model binding

public function fields()
{
    return [
        $this->email(),
    ];
}
public function email()
{
    $email_rule = optional($this->model)->exists
        ? ['required', 'email', Rule::unique('users', 'email')->ignore($this->model->id)]
        : 'required|email|unique:users,email';
    return Input::make('Email')
        ->type('email')
        ->prefix('@')
        ->rules($email_rule);
}

Dynamic realtime validation

  • You can change the fields default validation when the field is updated
  • When setting the rules in realtime, you have to use the form_data prefix. You also have to set the email column in Rules
  • In this case you have to apply realtimeValidationOff() on the field
public function updatedEmail($value)
{
    $email_rule = optional($this->model)->exists
        ? ['form_data.email' => [
            'required', 'email',
            Rule::unique('users', 'email')->ignore($this->model->id),
        ]]
        : ['form_data.email' => 'required|email|unique:users,email'];
    $this->rules['form_data.email'] = $email_rule;
    $this->validateOnly('form_data.email', $email_rule);
}
Clone this wiki locally