webmaster
webmaster

Hi Guys, I want to know how we can make a required field.

  • In fields.yaml I entered required: true
  • In model.php I entered: public $rule = [ 'name' => 'required' , 'slug' => 'required' , ];

but when I create form it submit without any error!

Last updated

Krisawzm
Krisawzm

The variable should be named $rules, not $rule.

You'll also need to use the Validation trait by adding use \October\Rain\Database\Traits\Validation; to the beginning of your class definition.

Example:

class MyModel extends Model
{
    use \October\Rain\Database\Traits\Validation;

    public $rules = [
        'name' => 'required'
    ];
}
webmaster
webmaster

Thanks it's my solution.

is it possible we define custom error message for each required field?

Krisawzm
Krisawzm

You can specify custom error messages in the $customMessages variable. Read the Laravel Documentation to see how you format the strings.

Example:

class MyModel extends Model
{
    use \October\Rain\Database\Traits\Validation;

    public $rules = [
        'name' => 'required'
    ];

    public $customMessages = [
        'name.required' => 'A name is required.'
    ];
}
webmaster
webmaster

Great, Thanks for your help.

ryan37023
ryan37023

Is there a solution to give conditional rule? for example, i don't want certain fields to be required when duplicating the event.

thiago33406
thiago33406

Reference: https://octobercms.com/docs/database/traits#dynamic-validation-rules

For conditional rules I know you can use

public function beforeValidate()
{
    if (!$this->is_remote) {
        $this->rules['latitude'] = 'required';
        $this->rules['longitude'] = 'required';
    }
}

I am experiencing issues using the trait and rules though. The error message is not showing up. All I get is an alert saying "error". My before validate method is also not being called. I am not sure what I am doing wrong.

class Job extends Model
{
    use \October\Rain\Database\Traits\Validation;

    /**
     * @var array Validation rules
     */
    public $rules = [
        'title'         => 'required',
    ];

    public $customMessages = [
        'title.required' => 'Job title is required!',
    ];

1-7 of 7