我已经创建了这个自定义类来验证我网站上的一些数字。
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
是有效的输入字段。
知道如何解决这个问题吗?
答案 0 :(得分:1)
我在Yii documentation中重新检查了这一点,似乎你必须添加一个带参数的数组来替换字符串中的占位符。但是,如果您只使用属性的默认占位符,则它应该默认工作。
您是否只有客户端验证问题?因为我现在也检查了Yii代码,似乎你的代码是正确的,并且应该工作(至少是服务器验证)。但是在客户端验证中,您只需将错误mesasage传递给JSON而不进行任何处理,因此{attribute}
不会替换任何地方。
尝试在return
$params['{attribute}']=$object->getAttributeLabel($attribute);
$error_message = strtr($error_message,$params));