2016-07-19 173 views
0

我很困惑,自定义验证规则是否需要返回true或false来触发。Laravel 4自定义验证规则

我正在验证一个电子邮件地址,以确保它已通过关系属于另一个模型。

Validator::extend('email_exists', function($attribute, $value, $parameter){ 
     $user = User::where('email', '=', $value)->with('clients')->first(); 
     //Does the user exits, and are they already a member of this client? 
     //We know this by looking at the client id, and comparing them the current ID. 
     if($user != NULL) { 
      if(in_array(Input::get('client_id'), $user->clients->lists('id'))) { 
       return false; 
      } else { 
       return true; 
      } 
     } else { 
      return true; 
     } 

}); 

什么我想上面,发现如果用户使用输入的电子邮件是否存在,如果它确实存在,然后检查电子邮件与任何客户,而如果这些客户端的ID匹配客户端ID在POST中,如果电子邮件存在并且与POST中的客户端ID相关我想返回一个错误,其他明智的我很高兴POST处理。

目前,我认为我允许任何事情通过。我是否正确使用自定义规则,如果我想抛出错误,应该返回什么?

+0

它看起来是正确的,你把这个代码放在服务提供者中吗?如果是这样的话,你是否记得在'config/app.php'中将服务提供者添加到提供者数组? – user3158900

+0

目前在我的控制器中是直的。 – Udders

+0

只要确保它在表单提交的控制器部分中,而不是负责构建表单的部分?在设置'$ user' var之前,也可以尝试添加'dd('test');'以查看它是否进入该部分。 – user3158900

回答

0

我认为你正在接近这个错误的方式。除了为单个用例扩展Validator类的压力之外,您应该考虑简单地将消息添加到消息包中,并将输入元素作为关键字。例如

$validator->messages()->add('client_id', 'This email is already associated with a client'); 

提示:我通常是一个规则阵列添加到我的模型和注入Validator类,所以我可以很容易地验证模型,而无需创建Validator的实例,或者写一个规则阵列中的所有的时间。