【发布时间】:2016-07-13 08:10:56
【问题描述】:
在我的 Yii2 应用程序中,我尝试使用自定义验证方法验证我用于用户名输入的字段,该方法检查该字段是否有空格。
class SomeModel extends Model
{
public $username;
public $email;
public $password;
public function rules()
{
return
[
// Other rules
[
[
'username',
'password',
],
function ($attribute, $params)
{
if (preg_replace('/\s+/', '', $this->attribute)) {
$this->addError($attribute, 'No white spaces allowed!');
}
},
],
],
}
无法解决的问题。记录保存时带有一些空格。
在视图中,这是字段:
<?= $form->field($model, 'username')->textInput(['class' => 'form-control', 'autocomplete' => 'off', 'placeholder' => 'Username'])->label(FALSE); ?>
【问题讨论】:
-
你试过filter
-
把
user_username改成username就像<?= $form->field($model, 'username')->textInput(['class' => 'form-control', 'autocomplete' => 'off', 'placeholder' => 'Username'])->label(FALSE); ?>一样 -
您想在用户名或密码包含空格时抛出错误?或者你想替换空格?
-
@wishu...ehm 抱歉,是的,它是该表单字段中的用户名(我复制错误)。 M. 我想抛出一个错误
-
@giovaZ 那么你应该使用 preg_match('/\s+/',$this->attribute)。 preg_replace 只是进行替换并返回带有替换字符的字符串,并且 if('string') 将始终返回 false。
标签: php validation yii2