PHPActiveRecord validates

Posted Mark的小试牛刀

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

什么是好的 PHP Active Record 库? [关闭]

Laravel 框架

laravel 可以做什么

laravel 可以做什么

laravel轻博客实战教程小学篇

CodeIgniter/PHP Active Record 不会增加整数