在 yii2 中的扩展模态中添加自定义消息到属性验证



我在 yii2 中有一个模态类,其规则定义为

return [
            [['charity_name', 'address', 'contact_name', 'title', 'dialling_code', 'phone_no', 'email', 'notes', 'added_by', 'created_at'], 'required'],
            [['dialling_code', 'phone_no', 'added_by', 'created_at', 'status'], 'integer'],
            [['charity_name', 'contact_name', 'email'], 'string', 'max' => 100],
            [['address', 'title'], 'string', 'max' => 200],
            [['notes'], 'string', 'max' => 255],
            [['charity_name'], 'unique'],
            [['added_by'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['added_by' => 'id']],
            [['dialling_code'], 'exist', 'skipOnError' => true, 'targetClass' => CountryDiallingCodes::className(), 'targetAttribute' => ['dialling_code' => 'id']],
        ];

我想将消息显示为"电话号码应该是数字",所以我将以下函数放在扩展类中

  public function rules() {
      $rules = parent::rules();
      $rules[] = [['phone_no'], 'integer', ['message'=>'Phone number should be numeric']];
      return $rules;
   }

但它似乎不起作用.请让我知道如何在扩展模态类中为属性添加自定义消息

public function rules() {
    $rules = parent::rules();
    $rules[] = [['phone_no'], 'integer', 'message'=>'Phone number should be numeric'];
    return $rules;
}

message中删除[]

您也可以添加pattern进行验证。

$rules[] = [['mobile_no'], 'match', 'pattern'=>"/^d{10}$/", 'message'=>'Phone number should be numeric'];

最新更新