Skip to content

BaseField Validation

TinaH edited this page Apr 28, 2021 · 5 revisions

Component validation attributes

You can use the field labels, or the field keys as attributes for validation messages. Default setting is to use the field labels. This can be overridden per field.

You can change this setting globally in the config file, or in the form components mount() method.

// in tall-forms config
'field-labels-as-validation-attributes' => true,
//in mount()
$this->$labelsAsAttributes = false;

BaseField attributes

->keyAsAttribute()

Use the field $key, as attribute for validation messages. This overrides the component $labelsAsAttributes setting.

->realtimeValidationOff()

Wait with field validation until the form is submitted.

  • The methods use case is for conditional validation on the updatedFoo() event hook. See "Dynamic realtime validation" below.
  • Consider using ->wire('wire:model.defer') instead.

->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