• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Mark的小试牛刀

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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;
	}

  

 

posted on 2017-05-09 18:20  我是天才啊  阅读(289)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3