简体   繁体   中英

Yii2 validation with XRegExp, \p{L} not working

I'm using Yii2 framework and I have a Validator that should do client-side validation. I have a regex that looks like this: /^[\\\\p{L}]+$/u for simplicity, but my actual regex is a bit more complicated, but the \\p{L} part is what causes the problems.

And so my code like this in the validator class:

public function clientValidateAttribute($model, $attribute, $view)
{
    $message = json_encode($this->message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    return <<<JS
    if (!XRegExp('/^[\\p{L}]+$/u').test(value)) {
        messages.push($message);
    }
JS;
}

Problem is, this always fails for \\p{L} but if I change the pattern for something like /^[AZ]+$/ it works flawlessly.

I'm using the 1.3.0 xregexp-all.js. It is added to in an AssetBundle class in \\assets\\AppAsset.php

I did notice while I was playing around with my regex, that when I made it wrong and was shown an exception, \\\\p{L} was interpreted as p{L} . So after some tries I've found out that for whatever reason I needed four backslashes to get it interpreted as \\p{L} . Final code that works:

public function clientValidateAttribute($model, $attribute, $view)
{
    $message = json_encode($this->message, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    return <<<JS
    if(!XRegExp('^[\\\\p{L}]+$').test(value)) {
        messages.push($message);
    }
JS;
}

在我的情况下\\p{L}被解释为p{L}所以我只是添加了一个反斜杠来转义p ,结果是\\\\p{L}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM