首页 > 代码库 > PHPActiveRecord validates

PHPActiveRecord validates

validates_presence_of

#检测是不是为空 为空的话可以抛出异常*Model类:static $validates_presence_of = array(    array(‘title‘, ‘message‘ => ‘不能为空‘));实例化后:$user = new User(array(‘name‘=>‘‘));$user->save();var_dump($user->errors->on(‘name‘)); #=> 不能为空

  


validates_size_of

#对字符串长度的限制*Model类:static $validates_size_of = array(    array(‘name‘,             ‘within‘ => array(1,5),              ‘too_short‘ => ‘too short!‘,             ‘too_long‘ => ‘should be short and sweet‘) );

  

validates_exclusion_of

#对词语的屏蔽*Model类:static $validates_exclusion_of = array(     array(‘name‘, ‘in‘ => array(‘god‘, ‘sex‘, ‘password‘, ‘love‘, ‘secret‘),‘message‘ => ‘should not be one of the four most used name‘));

  


validates_format_of

#正则匹配*Model类:static $validates_format_of = array(    array(‘email‘, ‘with‘ =>‘/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/‘)    array(‘password‘, ‘with‘ =>‘/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/‘, ‘message‘ => ‘is too weak‘));

  

validates_numericality_of

#对数字大小的限制*Model类:static $validates_numericality_of = array(    array(‘price‘, ‘greater_than‘ => 0.01),    array(‘state‘, ‘only_integer‘ => true),    array(‘shipping‘, ‘greater_than_or_equal_to‘ => 0),    array(‘discount‘, ‘less_than_or_equal_to‘ => 5, ‘greater_than_or_equal_to‘ => 0));

  

validates_uniqueness_of
  

#唯一性的限制*Model类:static $validates_uniqueness_of = array(array(‘name‘, ‘message‘ => ‘blah and bleh!‘));*实例化:User::create(array(‘name‘ => ‘Tito‘));$user = User::create(array(‘name‘ => ‘Tito‘));$user->is_valid(); # => false

 before_validation_on_create

#验证之前执行方法// setup a callback to automatically apply a tax	static $before_validation_on_create = array(‘apply_tax‘);	public function apply_tax()	{		if ($this->person->state == ‘VA‘)			$tax = 0.045;		elseif ($this->person->state == ‘CA‘)			$tax = 0.10;		else			$tax = 0.02;		$this->tax = $this->price * $tax;	}

  

 

PHPActiveRecord validates