Creating new validation rule to extend alpha dash with spaces

parent b29d1347
<?php
namespace Modules\Media\Tests;
use Illuminate\Container\Container;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Translation\FileLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory as Validator;
use Modules\Media\Validators\AlphaDashWithSpaces;
final class AlphaDashWithSpacesTest extends MediaTestCase
{
public function test_it_creates_instance_of_validator()
{
$obj = new AlphaDashWithSpaces();
$this->assertInstanceOf(AlphaDashWithSpaces::class, $obj);
}
/** @test */
public function it_validates_rule_is_valid()
{
$this->assertTrue($this->buildValidator('My-Folder')->passes());
$this->assertTrue($this->buildValidator('My Folder')->passes());
$this->assertTrue($this->buildValidator('My Folder-isCool')->passes());
}
/** @test */
public function it_validates_invalid_rule()
{
$this->assertFalse($this->buildValidator('My-Folder @email')->passes());
$this->assertFalse($this->buildValidator('My-Folder @email|}{')->passes());
}
/** @test */
public function it_has_correct_error_message()
{
$message = $this->buildValidator('My-Folder @email|}{')->getMessageBag();
$this->assertEquals(
'The name may only contain letters, numbers, dashes and spaces.',
$message->get('name')[0]
);
}
public function buildValidator($folderName)
{
$app = new Container();
$app->singleton('app', 'Illuminate\Container\Container');
$translator = new Translator(new FileLoader(new Filesystem(), null), 'en');
$validator = (new Validator($translator))->make(['name' => $folderName], [
'name' => ['required', new AlphaDashWithSpaces()],
]);
return $validator;
}
}
<?php
namespace Modules\Media\Validators;
use Illuminate\Contracts\Validation\Rule;
class AlphaDashWithSpaces implements Rule
{
/**
* Determine if the validation rule passes.
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if (! is_string($value) && ! is_numeric($value)) {
return false;
}
return preg_match('/^[\pL\pM\pN_\s-]+$/u', $value) > 0;
}
/**
* Get the validation error message.
* @return string
*/
public function message()
{
return 'The :attribute may only contain letters, numbers, dashes and spaces.';
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment