Yii2 用户自定义验证手机号码



我是Yii2的新手。我想通过自定义验证功能验证手机号码。如何在 Yii2 中验证移动号码,如何使用用户定义的规则到 yii2 和 如何在表单发布后向 yii2 中的任何属性添加错误消息?提前致谢

您需要编辑模型。假设您有以下模型:

class User extends ActiveRecord implements IdentityInterface
{
...
/**
* @inheritdoc
*/
public function rules()
{
return [
[['email', 'password', 'id'], 'required'],
[['email', 'username'], 'unique'],
['mobile', 'customValidation'] //<----this will be your custom validation
}
public function customValidation(){
//perform your validation here
if(/*has error*/){
$this->addError("mobile","Your mobile number is not valid.");
}
}

}

addError 方法的第一个参数是要将错误添加到的 atribute ,第二个参数是要显示的消息。

希望这对;)有所帮助

也许这可以帮助任何人。

在 Yii2 中使用模式匹配并验证您的输入字段。

如果数字少于/超过 10 位,它将检查并返回警报消息。

['mobile', 'match', 'pattern'=>"/^[0-9]{3}[0-9]{3}[0-9]{2}[0-9]{2}$/",'message'=> 'Not Correct Format - mobile number should have 10 digits.'],

最新更新