Skip to content

Commit

Permalink
Pattern validation for text fields #2041
Browse files Browse the repository at this point in the history
  • Loading branch information
Nico Hoffmann committed Sep 15, 2019
1 parent 3e63f93 commit 5f94cdd
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 2 deletions.
3 changes: 2 additions & 1 deletion config/fields/text.php
Expand Up @@ -98,6 +98,7 @@
],
'validations' => [
'minlength',
'maxlength'
'maxlength',
'pattern'
]
];
7 changes: 6 additions & 1 deletion panel/src/components/Forms/Input/TextInput.vue
Expand Up @@ -96,13 +96,18 @@ export default {
}
},
validations() {
const match = (value) => {
return (!this.required && value.length === 0) || !this.$refs.input.validity.patternMismatch;
};
return {
value: {
required: this.required ? required : true,
minLength: this.minlength ? minLength(this.minlength) : true,
maxLength: this.maxlength ? maxLength(this.maxlength) : true,
email: this.type === "email" ? email : true,
url: this.type === "url" ? url : true
url: this.type === "url" ? url : true,
pattern: this.pattern ? match: true,
}
};
}
Expand Down
13 changes: 13 additions & 0 deletions src/Form/Validations.php
Expand Up @@ -107,6 +107,19 @@ public static function minlength(Field $field, $value): bool
return true;
}

public static function pattern(Field $field, $value): bool
{
if ($field->isEmpty($value) === false && $field->pattern() !== null) {
if (V::match($value, '/' . $field->pattern() . '/i') === false) {
throw new InvalidArgumentException(
V::message('match')
);
}
}

return true;
}

public static function required(Field $field, $value): bool
{
if ($field->isRequired() === true && $field->save() === true && $field->isEmpty($value) === true) {
Expand Down
28 changes: 28 additions & 0 deletions tests/Form/ValidationsTest.php
Expand Up @@ -186,6 +186,34 @@ public function testMinLengthInvalid()
Validations::minlength($field, 'test');
}

public function testPatternValid()
{
$page = new Page(['slug' => 'test']);
$field = new Field('test', [
'pattern' => '^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$',
'model' => $page
]);

$this->assertTrue(Validations::pattern($field, '#fff'));
$this->assertTrue(Validations::pattern($field, '#222'));
$this->assertTrue(Validations::pattern($field, '#afafaf'));
$this->assertTrue(Validations::pattern($field, '#34b3cd'));
}

public function testPatternInvalid()
{
$this->expectException('Kirby\Exception\InvalidArgumentException');
$this->expectExceptionMessage('The value does not match the expected pattern');

$page = new Page(['slug' => 'test']);
$field = new Field('test', [
'pattern' => '^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$',
'model' => $page
]);

Validations::pattern($field, '#MMM');
}

public function testRequiredValid()
{
$page = new Page(['slug' => 'test']);
Expand Down

0 comments on commit 5f94cdd

Please sign in to comment.