【问题标题】:Yii2 validate usernameYii2 验证用户名
【发布时间】: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就像&lt;?= $form-&gt;field($model, 'username')-&gt;textInput(['class' =&gt; 'form-control', 'autocomplete' =&gt; 'off', 'placeholder' =&gt; 'Username'])-&gt;label(FALSE); ?&gt;一样
  • 您想在用户名或密码包含空格时抛出错误?或者你想替换空格?
  • @wishu...ehm 抱歉,是的,它是该表单字段中的用户名(我复制错误)。 M. 我想抛出一个错误
  • @giovaZ 那么你应该使用 preg_match('/\s+/',$this->attribute)。 preg_replace 只是进行替换并返回带有替换字符的字符串,并且 if('string') 将始终返回 false。

标签: php validation yii2


【解决方案1】:
class SomeModel extends Model
{
  public $username;
  public $email;
  public $password;

  public function rules()
  {
    return 
    [
       // Other rules
     [
            [
                'username',
                'password',
            ],
            function ($attribute, $params)
            {
                //returns true / false (preg_replace returns the string with replaced matched regex)
                if (preg_match('/\s+/',$this->attribute)) {
                     $this->addError($attribute, 'No white spaces allowed!');
                }

            },
        ],
    ],
  }

【讨论】:

  • 方法是对的,但我不认为这是我编写验证的方式。我已经尝试了其他方法,例如“过滤器”,使用您的功能并编辑出现“用户名”字段的其他规则。我确定我正在用户名字段中进行操作(我已经在我的视图中发布了部分代码)。但我不知道为什么它不验证。
  • 你有前端验证吗?
  • 另外,你能展示一下你是如何使用 validate 方法的吗?
  • 我在我的代码中看到了一个导致这种验证方法出现问题的字段,我已将您的答案签署为正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多