Skip to content

Commit

Permalink
Allow custom validation messages
Browse files Browse the repository at this point in the history
  • Loading branch information
djonasm committed Jan 7, 2019
1 parent 9b29304 commit 06a337a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/MongolidModel.php
Expand Up @@ -135,7 +135,7 @@ public function isValid()
}

// Creates validator with attributes and the rules of the object
$validator = app(ValidationFactory::class)->make($attributes, $rules);
$validator = app(ValidationFactory::class)->make($attributes, $rules, $this->messages());

// Validate and attach errors
if ($hasErrors = $validator->fails()) {
Expand Down Expand Up @@ -167,6 +167,15 @@ public function rules(): array
return $this->rules ?? [];
}


/**
* Get custom messages for validation errors.
*/
public function messages(): array
{
return [];
}

/**
* Returns the database object (the connection).
*/
Expand Down
28 changes: 28 additions & 0 deletions tests/MongolidModelTest.php
Expand Up @@ -52,6 +52,34 @@ public function testShouldNotValidateWithUnattendedRules()
$this->assertEquals($expectedErrors, $model->errors()->all());
}

public function testShouldValidateRulesWithCustomMessage()
{
// Set
$model = new class() extends MongolidModel {
protected $rules = [
'name' => 'required',
];

public function messages()
{
return [
'name.required' => 'The name must be fielded.',
];
}
};

$expectedErrors = [
'The name must be fielded.',
];

// Actions
$result = $model->isValid();

// Assertions
$this->assertFalse($result);
$this->assertEquals($expectedErrors, $model->errors()->all());
}

public function testValidateShouldSkipUnchangedHashedAttributes()
{
// Set
Expand Down

0 comments on commit 06a337a

Please sign in to comment.