使用 Laravel 验证验证布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23200839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:23:58  来源:igfitidea点击:

Validating boolean with Laravel Validation

validationlaravellaravel-4

提问by user391986

I have a login form with

我有一个登录表单

username, passwordand remember me

usernamepasswordremember me

remember meis a checkbox (true or false).

remember me是一个复选框(真或假)。

How do I create the validation rule in Laravel? http://laravel.com/docs/validation#basic-usage

如何在 Laravel 中创建验证规则? http://laravel.com/docs/validation#basic-usage

The only relevant one it seems was inand you specify the values but the values in this case are booleans and using this method they would be specified as string?

唯一相关的似乎是in您指定了值,但在这种情况下,值是布尔值,使用此方法将它们指定为字符串?

in:true,false

in:true,false

回答by morphatic

There's a validator for boolean.Assuming you're using one of the packages that simplifies model validation, e.g. EsensiModel, it's as simple as adding the following to your Model:

有一个验证器boolean假设您使用的是简化模型验证的包之一,例如EsensiModel只需将以下内容添加到您的Model:

protected $rules = [
    'email'       => 'required|email',
    'password'    => 'required',
    'remember_me' => 'boolean',
];

回答by The Alpha

You may try something like this:

你可以尝试这样的事情:

$rules = array('email' => 'required|email', 'password' => 'required');
$inputs = array(
    'email' => Input::get('email'),
    'password' => Input::get('password')
);
$validator = Validator::make($inputs, $rules);

if($validator->fails()) {
    return Redirect::back()->withInput()->withErrorts($validator);
}
else {
    $remember = Input::get('remember', FALSE);
    if(Auth::attempt($inputs, !!$remember)) {
        // Log in successful
        return Redirect::to('/'); // redirect to home or wherever you want
    }
}

I've used emailwhich is recommended but if you use usernameother than emailthen just change the emailto usernameand in the rule for usernameuse something like this:

我已经使用了email推荐的但如果你使用username其他的email只是改变规则中的emailtousername和 inusername使用这样的东西:

'username' => 'required|alpha|min:6' // Accepts only a-z and minimum 6 letters