Laravel4:检查插入的电子邮件是否格式正确

时间:2013-09-02 12:39:37

标签: forms testing laravel laravel-4

在我的应用程序中,有一个订阅时事通讯的小表格。 表单只有一个字段:email。

我希望当条目不是正确的电子邮件格式时,而不是抛出laravel错误:给定[fghfghfhf]的邮箱中的地址不符合RFC 2822,3.6.2。

我想更优雅地给出验证错误。

我如何定义此规则?

谢谢!

编辑:

这是我的NewsletterUser模型:

class NewsletterUser extends Eloquent {

protected $table = 'newsletterusers';

protected $guarded = array();

public static $rules = array(

    'email' => 'required | email | unique:newsletterusers'

    );

 public static $messages = array(
        'email' => 'You already subscribed',
        'empty' => 'Insert the mail, please'
       );

}

这是Controller中的订阅方法:

 public function subscription()
{
    $input = Input::all();

    $validation = Validator::make($input, NewsletterUser::$rules, NewsletterUser::$messages);

    if($validation->passes())
    {
       // subscription stuff
    }

    return Redirect::back()->withInput()->withErrors($validation)->with('message','Insert the mail, please');
}

1 个答案:

答案 0 :(得分:0)

只需定义custom error message

即可
$messages = array(
    'email' => 'Address in mailbox given :attribute does not comply with RFC 2822, 3.6.2.',
);

$validator = Validator::make($input, $rules, $messages);
相关问题