做有谁知道我可以申请规则的Yii模型的输入必须大于0值,没有任何自定义方法添加规则..我们如何能够在Yii中模型的输入必须大于0
,如:
public function rules()
{
return array(
....
....
array('SalePrice', 'required', "on"=>"sale"),
....
....
);
}
许多感谢..
做有谁知道我可以申请规则的Yii模型的输入必须大于0值,没有任何自定义方法添加规则..我们如何能够在Yii中模型的输入必须大于0
,如:
public function rules()
{
return array(
....
....
array('SalePrice', 'required', "on"=>"sale"),
....
....
);
}
许多感谢..
简单用一个自定义的验证方法
array('SalePrice', 'greaterThanZero')
public function greaterThanZero($attribute,$params)
{
if ($this->$attribute<=0)
$this->addError($attribute, 'Saleprice has to be greater than 0');
}
方式
array('SalePrice', 'numerical', 'min'=>1)
我看到它是有代价的,所以你可以使用0.01(一分钱),像这样的最小值:
array('SalesPrice', 'numerical', 'min'=>0.01),
请注意,此解决方案不验证输入的号码是有代价的,只是它是> 0.01
看起来很酷但'1.2345689'值将通过这个规则..是不是有效的价格。您的验证只会限制0.009这种不属于真实场景的情况。 – 2014-12-07 16:44:50
OP的背景是价格,那么你建议一个很酷的,但错误验证专门为**价格** ..然后原谅你的自我,它可能不适合价格..但工作..在一些一般情况下..这不是什么OP问,而不是你在暗示!? 您的帖子应该被修改或删除,因为它提供了很酷的外观,但却完全错误的解决方案。并且在代码的复制粘贴之后不会立即被注意到,所以它变得邪恶。 – 2015-01-19 11:25:51
@ d.raev实际上,OP没有指定规则需要验证价格,而是要求“我怎样才能在Yii模型中应用规则输入必须大于0值”,并且做了两次,一次在标题,然后再次在体内。这是我选择了价格的一部分。而对于什么值得1.2345689是>零,所以应该通过OP要求“输入必须大于0值”的规则。感谢您的建议,我会添加一个注释,即使没有要求,这也不会验证该数字是价格。 – sdjuan 2015-01-27 07:22:56
我通过正则表达式处理了这个问题,可能会有帮助..
array('SalePrice', 'match', 'not' => false, 'pattern' => '/[^a-zA-Z0]/', 'message' => 'Please enter a Leader Name', "on"=>"sale"),
千恩万谢@sdjuan & @Ors您的帮助和时间..
不客气:) – adamors 2012-03-30 08:33:02
我知道我是太晚了这一点。但是,仅仅以供将来参考,你可以使用这个类也
<?php
class greaterThanZero extends CValidator
{
/**
* 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)
{
$value=$object->$attribute;
if($value <= 0)
{
$this->addError($object,$attribute,'your password is too weak!');
}
}
/**
* 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)
{
$condition="value<=0";
return "
if(".$condition.") { messages.push(".CJSON::encode($object->getAttributeLabel($attribute).' should be greater than 0').");
}";
}
}
?>
只要确保这个类在使用前进口。
你可以用这一个了:
array('SalePrice', 'in','range'=>range(0,90))
我认为min属性用于文本框中的最小长度..我需要验证的数值必须大于0不需要长度 – 2012-03-29 11:53:49
不,如果验证器是'数字',则min表示下限。看到这里:http://www.yiiframework.com/doc/api/1.1/CNumberValidator#min-detail – adamors 2012-03-29 18:31:35
有一个CCompareValidator,可以开箱即用。 – Arth 2015-05-07 14:42:41