如何在Yii 2.0中验证数据库的输入字段?

问题描述:

Suppose I have a field name id and I want the user to enter some integer in the id field but at the same time I want to check that id against the database whether it exists or not. If it exists then it should show some error.

Is there a function to achieve this in Yii 2.0?

Any help would be greatly appreciated. Thank you!

假设我有一个字段名称id,我希望用户在id字段中输入一些整数但是相同 我想在数据库中检查该ID是否存在。 如果它存在则应该显示一些错误。 p>

在Yii 2.0中是否有实现此功能的功能? p>

任何帮助都将不胜感激。 谢谢! p> div>

If this is from a model, you can have a unique rule to it in the validation rules.

In your model, you have a rules() function:

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
        array('name', 'required'),
        array('some_id', 'unique'),
    );
}