Rozbudowa walidatora – dodajemy regułę, która sprawdza, czy dana wartość jest e-mailem. Do dzieła!
Przypomnijmy, na czym skończyliśmy:
<?php
/*
$form_rules = [
'email' => ['required', 'email'],
'password' => ['required'],
'confirmPassword' => ['required', 'match:password']
];
*/
$form_data = [
'email' => 'john.doe@gmail.com',
'password' => md5('helloworld'),
'confirmPassword' => md5('helloworld')
];
interface RuleInterface
{
public function validate(array $data, string $field, array $params): bool;
public function getMessage(array $data, string $field, array $params): string;
}
class RequiredRule implements RuleInterface
{
public function validate(array $data, string $field, array $params): bool
{
return !empty($data[$field]);
}
public function getMessage(array $data, string $field, array $params): string
{
return "Field {$field} is missing!";
}
}
$field = 'email';
$required_rule = new RequiredRule;
$field_exists = $required_rule->validate($form_data, $field, []);
if(!$field_exists){
echo $required_rule->getMessage($form_data, $field, []);
}
Tworzymy klasę EmailRule:
class EmailRule implements RuleInterface
{
public function validate(array $data, string $field, array $params): bool
{
return (bool) filter_var($data[$field], FILTER_VALIDATE_EMAIL);
}
public function getMessage(array $data, string $field, array $params): string
{
return "Invalid email";
}
}
Z rozpędu URLRule też możemy utworzyć:
class UrlRule implements RuleInterface
{
public function validate(array $data, string $field, array $params): bool
{
return (bool) filter_var($data[$field], FILTER_VALIDATE_URL);
}
public function getMessage(array $data, string $field, array $params): string
{
return "Invalid URL";
}
}
Pora wypróbować:
<?php
/*
$form_rules = [
'email' => ['required', 'email'],
'password' => ['required'],
'confirmPassword' => ['required', 'match:password']
];
*/
$form_data = [
'email' => 'john.doe@gmail.com',
'password' => md5('helloworld'),
'confirmPassword' => md5('helloworld')
];
//(...)
class EmailRule implements RuleInterface
{
//(...)
}
class UrlRule implements RuleInterface
{
//(...)
}
$field = 'email';
$rule = new EmailRule;
$is_email = $rule->validate($form_data, $field, []);
if(!$is_email){
echo $rule->getMessage($form_data, $field, []);
}
Nic nie widać – znaczy działa. Ale sprawdźmy, czy jest Urlem:
<?php
/*
$form_rules = [
'email' => ['required', 'email'],
'password' => ['required'],
'confirmPassword' => ['required', 'match:password']
];
*/
$form_data = [
'email' => 'john.doe@gmail.com',
'password' => md5('helloworld'),
'confirmPassword' => md5('helloworld')
];
//(...)
class EmailRule implements RuleInterface
{
//(...)
}
class UrlRule implements RuleInterface
{
//(...)
}
$field = 'email';
$rule = new UrlRule;
$is_url = $rule->validate($form_data, $field, []);
if(!$is_url){
echo $rule->getMessage($form_data, $field, []);
}
//Invalid URL
Match w następnym odcinku.