phalcon验证cirillic utf8

时间:2017-08-13 10:06:17

标签: validation utf-8 phalcon

我在Phalcon模型中尝试验证Alnum。但是当我在Cyrillic(utf8)

中输入符号时,我得不到正确的验证
$validation->add(
    'title',
    new \Phalcon\Validation\Validator\Alnum([
        "message" => 'Поле Город содержит недопустимые символы',
    ])
);

1 个答案:

答案 0 :(得分:0)

Phalcon的验证服务使用的是ctype_alnum函数内置的PHP( as seen here ),它不支持多字节字符串。

用于测试的快速代码段:

$validation = new \Phalcon\Validation(); 
$validation->add(
    'name',
    new \Phalcon\Validation\Validator\Alnum(
        [
            'message' => 'Validation failed',
        ]
    )
);
$words = [
    'test1234',
    't__est1234',
    'тест123',
]; 
echo '<h2>Phalcon Validation</h2>';
foreach ($words as $word) {
    $messages = $validation->validate(['name' => $word]);
    if (count($messages)) {
        echo '[N] '. $word, '<br>';
    } else {
        echo '[Y] '. $word, '<br>';
    }
}

echo '<h2>PHP `ctype_alnum`</h2>';
foreach ($words as $word) {
    if (ctype_alnum($word)) {
        echo '[Y] '. $word, '<br>';
    } else {
        echo '[N] '. $word, '<br>';
    }
}

<强>结果:

Phalcon Validation
[Y] test1234
[N] t__est1234
[N] тест123


PHP `ctype_alnum`
[Y] test1234
[N] t__est1234
[N] тест123

我担心您必须使用preg_match来解决您的问题。快速样本:

preg_match("/^[a-zA-Z\p{Cyrillic}0-9\s\-]+$/u", $string);

来源:Using Arabic characters with ctype_alnumHow to use ctype_alpha with UTF-8

最后,这里有关于如何创建自己的验证器的信息:https://docs.phalconphp.com/en/latest/validation#validators

更新:来自评论的@Vladimir Kompaniec解决方案!

$validator->add('city', new Callback([ 
    'callback' => function () { 
        if (empty($this->subway)) { 
            return true; 
        } 
        return (0 != preg_match("/[\w\d\s\-А-Яа-я]+/u", $this->subway)); 
    }, 
    'message' => 'Поле метро содержит недопустимые символы', 
    'cancelOnFail' => true, 
]));