如何验证控制台命令提示符输入

时间:2017-06-08 03:56:50

标签: laravel validation command laravel-5.4

按照控制台命令,我提示输入。我想验证用户输入。我怎么能这样做?

我查看了this plugin。但它看起来像验证参数&选项。不是交互式输入。

CreateClient.php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateClient extends Command {
    ...

    public function handle() {
        $name   = $this->ask('Enter name ');
        $email  = $this->ask('Enter email ');
        $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

        // Validate user input
        $this->info('Validating user inputs');

       // How to validate email & date format ?
    }
}

更新

是的我知道Validator,但关注的是验证会停止用户旅程。用户从头开始重启。是否可以为每个问题附加验证,因此验证将立即进行并提示再次输入。

当我没有输入任何值时,我注意到以下内容,我想知道如何提供更多验证规则。

enter image description here

提前致谢。

5 个答案:

答案 0 :(得分:2)

一种方法是使用FILTER_VALIDATE_EMAILCarbon

public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    // How to validate email & date format ?
    $email_status = filter_var($email, FILTER_VALIDATE_EMAIL);

    if (!$email_status) {
        // Invalid EMAIL
    }

    if (\Carbon::createFromFormat('YOUR DATE FORMAT', $date) === false) {
        // Invalid date
    }

}

另一种方法是@btl使用Validator

所说的
public function handle() {
    $name   = $this->ask('Enter name ');
    $email  = $this->ask('Enter email ');
    $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

    // Validate user input
    $this->info('Validating user inputs');

    $data = array(
        'email' => $email,
        'date'  => $date
    );

    $rules = array(
        'email' => 'required|email',
        'date'  => 'required|date',
    );

    $validator = \Validator::make($data, $rules);

    if ($validator->fails()) {
        $messages = $validator->messages();
    }

}

答案 1 :(得分:2)

以下是使用Laravel验证器的另一种方法。

我的自定义方法validate_cmd有两个参数:

  1. Command方法(问,秘密,选择......)作为匿名函数
  2. 一系列规则
  3. 如果验证失败,将再次调用Command方法。

    当然你想把它放在特质中。     

    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    use Validator;
    
    class CreateClient extends Command {
    
        public function handle() {
    
            $name = $this->validate_cmd(function() {
                return $this->ask('Enter name');
            }, ['name','required']);
    
            $email = $this->validate_cmd(function() {
                return $this->ask('Enter email');
            }, ['email','required|email']);
    
            $date = $this->validate_cmd(function() {
                return $this->ask('Enter date [Eg: 2016-01-01 00:00:00]');
            }, ['date','required']);
    
        }
    
        /**
         * Validate an input.
         *
         * @param  mixed   $method
         * @param  array   $rules
         * @return string
         */
        public function validate_cmd($method, $rules)
        {
            $value = $method();
            $validate = $this->validateInput($rules, $value);
    
            if ($validate !== true) {
                $this->warn($validate);
                $value = $this->validate_cmd($method, $rules);
            }
            return $value;
        }
    
        public function validateInput($rules, $value)
        {
    
            $validator = Validator::make([$rules[0] => $value], [ $rules[0] => $rules[1] ]);
    
            if ($validator->fails()) {
                $error = $validator->errors();
                return $error->first($rules[0]);
            }else{
                return true;
            }
    
        }
    
    }
    

答案 2 :(得分:1)

创建Validator实例并设置相应的规则。

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Validator.html

具体来说,请参阅make()方法。

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Factory.html

public function handle()
{
    $name = $this->ask('Enter name ');
    $validator = \Validator::make(['name' => $name], ['name' => 'required|string']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $email = $this->ask('Enter email ');
    $validator = \Validator::make(['email' => $email], ['email' => 'required|email']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $date = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');
    $validator = \Validator::make(['date' => $date], ['date' => 'required|datetime']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }

    // so something with $message
}

答案 3 :(得分:1)

这就是我解决它的方法。

由于类\Symfony\Component\Console\Style\SymfonyStyle支持将验证回调作为第三个参数传递,我编写了一个下面的函数并调用它。

/**
 * Prompt the user for input.
 *
 * @param  string $question
 * @param  string $default
 * @param  callable|null $validator
 * @return string
 */
public function askWithValidation($question, $default = null, $validator = null)
{
    return $this->output->ask($question, $default, $validator);
}

一般验证功能

use Validator;

/**
 * Validates the user input
 *
 * @param string $attribute
 * @param string $validation
 * @param string $value
 * @throws Exception
 * @return string
 */
protected function validateInput(string $attribute, string $validation, $value)
{
    if (! is_array($value) && ! is_bool($value) && 0 === strlen($value)) {
        throw new \Exception('A value is required.');
    }

    $validator = Validator::make([
        $attribute => $value
    ], [
        $attribute => $validation
    ]);

    if ($validator->fails()) {
        throw new \Exception($validator->errors()->first($attribute));
    }

    return $value;
}

致电:

$contactEmail = $this->askWithValidation('Enter contact email ', null, function ($value) {
    return $this->validateInput('contactEmail', 'email', $value);
});

答案 4 :(得分:0)

这是Erevald的略微修改版本,因为我也需要类似的功能。

public function validate_console($method, $rules)
{
    $value = $method();
    $validate = $this->validateInput($rules, $value);

    if ($validate !== true) {
        $messages = collect($validate->messages())->flatten()->all();
        foreach ($messages as $failure) {
            $this->warn($failure);
        }
        $value = $this->validate_console($method, $rules);
    }
    return $value;
}

public function validateInput($rules, $value)
{
    $validator = Validator::make([key($rules) => $value], $rules);
    if ($validator->fails()) {
        return $validator->errors();
    }else{
        return true;
    }
}

用法:

$client_name = $this->validate_console(function() {
        return $this->ask('What should I call you? (Client Name)');
    }, ['client_name' => 'email|min:4']);

输出:

The client name must be a valid email address.
The client name must be at least 4 characters.