doutingyou2198 2018-09-15 22:24
浏览 81
已采纳

如何在Laravel中创建和使用更多特定于域的验证规则?

First of all, I am really in the beginner stage of Laravel. So, please excuse me and help me out.

I am trying to build an app using just Laravel (for learning purpose) where I am creating a Form using the Laravel Collective. I have learnt how to create a Form and send those values to Database and show it on the site.

However, what I am trying to do is I want to run few functions for one of the input (Suppose if a string field called "operator" has this value-> "+" then it will run the Addition function.) My approach is this: Create a Controller and add this public function addition($operator, $value1, $value2) in the function check if($operator== '+') then do this. Am I going in the right direction?

I have one more queries, I know how to validate the fields of a form by doing this for example in the store function of a controller : $this->validate(request, ['text'=> 'required|max:999']);

What I am trying to figure out is how to just make sure that only the Four Major Arithmetic Operators are allowed to take as an Input. Otherwise it won't work. So, can you guys guide me on this?

  • 写回答

1条回答 默认 最新

  • dtqpw68806 2018-09-16 01:32
    关注

    There are many ways to achive this and each will have pros and cons. The following might be a bit advanced if you are totally new to Laravel, but I'm sure that you will grasp the idea if you take a look to the documentation, as it's pretty easy to understand and intuitive.

    I'll suggest you to:

    • Create a custom validation rule to use in your controller
    • Declare this custom validation in a service provider
    • Use it in your controller

    Create a custom validation rule

    Imagine you want to check if certain input value is an actual arithmetic operator. There are many ways to do this in PHP. Here a few:

    if($value == '+' || $value == '-' || $value == '*' || $value '/')
    {
      // It IS a valid operator
    }
    

    Another way, as suggested in above comments is to use a switch:

    switch($value)
    {
       case '+':
       case '-':
       case '*':
       case '/':
          // it IS a valid operator
          break;
       default:
          // otherwise, it is NOT
    
    }
    

    I personally prefer a lookup in array:

    in_array($value, ['+', '-', '*', '/']);
    

    Of course, there may exist many other ways.

    Feel free to adopt the one that turns out to be clearer to you and you'll be able to refactor later as you learn more programming techniques.

    So now that you can distinguish an operator from anything else, you can make use of a custom validation rule that implements this code:

        Validator::extend('operator', function ($attribute, $value, $parameters, $validator) {
            return in_array($value, ['+', '-', '*', '/']);
        });
    

    Note that we have called it operator, but you can pick any name of your will. Try to keep it clean and intuitive. A few alternatives: valid_operator, arithmetic_operator, etc.

    Declare the rule in a service provider

    But in order to actually use the rule, you need to execute this code somewhere. A good place to start is in the boot() method of a service provider. You can use your AppServiceProvider, and you can always move it somewhere else (i.e. a more dedicated service provider) as you learn how to structure your application.

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Illuminate\Support\Facades\Validator;
    
    class AppServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            Validator::extend('operator', function ($attribute, $value, $parameters, $validator) {
                return in_array($value, ['+', '-', '*', '/']);
            });
        }
    
        /**
         * Register the service provider.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    

    Use it in controller

    As you now have your custom rule you can use it like this:

    $this->validate($request, ['text'=> 'required|operator']);
    

    Final words: Remember this is not the only way to do it. It is one of the possible options that Laravel suggests from it's documentation. In the end, it's always up to you. Try to understand each piece, always read the documentation as it's very helpful, and try to split your problem into steps. Code the least that works for you and always consider an I'll be back for refactor.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题