如何进行名称验证,我想在此字段中仅填写字母

时间:2018-08-13 15:34:58

标签: yii2

验证输入的代码:

public function rules() { 
    return [ [['name', 'email', 'subject', 'content'], 'required'], 
             [['date_added'], 'safe'],
             [['email', 'subject'], 'string', 'max' => 255], [['email'], 'email'], 
]; } 

2 个答案:

答案 0 :(得分:1)

您可以使用匹配模式

    public function rules() { 
    return [ [['name', 'email', 'subject', 'content'], 'required'], 
             [['date_added'], 'safe'],
             [['email', 'subject'], 'string', 'max' => 255], [['email'], 'email'], 
             [['name', 'match', 'pattern' => '/^[a-zA-Z]+$/', 
              'message' => 'Your username can only contain alphabetic characters']]

]; } 

答案 1 :(得分:1)

托盘:

    public function rules() { 
        return [ [['name', 'email', 'subject', 'content'], 'required'], 
                 ['name','match', 'pattern' => '[a-zA-Z][a-zA-Z., ]+$/;',
                'message' => 'Name can only contain Alphabet and Spaces only'],
                 [['date_added'], 'safe'],
                 [['email', 'subject'], 'string', 'max' => 255], [['email'], 'email'], 
    ]; }