自定义Yii验证类
我创建了这个自定义类来验证我网站上的一些数字自定义Yii验证类,yii,Yii,我创建了这个自定义类来验证我网站上的一些数字 class EPriceValidator extends CValidator { public $number_type; /* * Regular Expressions for numbers */ private $default_pattern = '/[^0-9,.]/'; private $price_pattern = '/[
class EPriceValidator extends CValidator
{
public $number_type;
/*
* Regular Expressions for numbers
*/
private $default_pattern = '/[^0-9,.]/';
private $price_pattern = '/[^0-9,.]/';
/*
* Default error messages
*/
private $default_msg = '{attribute} is an invalid number.';
private $price_msg = '{attribute} is an invalid price.';
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object,$attribute)
{
// check the strength parameter used in the validation rule of our model
if ($this->number_type == 'price')
{
$pattern = $this->price_pattern;
$error_message = $this->price_msg;
}
else {
$pattern = $this->default_pattern;
$error_message = $this->default_msg;
}
// extract the attribute value from it's model object
$value=$object->$attribute;
if(!preg_match($pattern, $value))
{
$this->addError($object,$attribute, $error_message);
}
}
/**
* Implementing Client Validation
*
* Returns the JavaScript needed for performing client-side validation.
* @param CModel $object the data object being validated
* @param string $attribute the name of the attribute to be validated.
* @return string the client-side validation script.
* @see CActiveForm::enableClientValidation
*/
public function clientValidateAttribute($object,$attribute)
{
// check the strength parameter used in the validation rule of our model
if ($this->number_type == 'price')
{
$pattern = $this->price_pattern;
$error_message = $this->price_msg;
}
else
{
$pattern = $this->default_pattern;
$error_message = $this->default_msg;
}
$condition="value.match(".$pattern.")";
return "
if(".$condition.") {
messages.push(".CJSON::encode($error_message).");
}
";
}
}
它很好用。但是如何使它显示错误的正确字段名呢?现在,当在客户端检测到错误时,将显示clientValidateAttribute()
{attribute} is an invalid number.
而不是
Total orders is an invalid number.
其中,Total orders
是有效的输入字段
知道如何解决这个问题吗?我在Yii中重新检查了这个问题,似乎您必须添加一个带有参数的数组来替换字符串中的占位符。但是,如果仅为属性使用默认占位符,则默认情况下它应该可以工作 您是否只有客户端验证的问题?因为我现在还检查了Yii代码,看起来您的代码是正确的,应该可以工作(至少是服务器验证)。但是在客户端验证中,您只需将错误消息传递给JSON,而不进行任何处理,因此,
{attribute}
不会在任何地方被替换。
在返回之前,尝试将其添加到youc客户端验证中
$params['{attribute}']=$object->getAttributeLabel($attribute);
$error_message = strtr($error_message,$params));