Home > Software engineering >  Laravel custom validation for three inputs
Laravel custom validation for three inputs

Time:08-16

I need to make a custom validation rule where for these three inputs where net_weight = loaded_weight - empty_weight

<fieldset >
   <div >
      <label for="text">empty weight</label>
      <input type="number"  id="empty_weight"
         name="empty_weight" min="15000" max="35000" step="20" oncopy="return false"
         onpaste="return false">
   </div>
</fieldset>
<fieldset>
   <legend >loaded weight</legend>
   <div >
      <input type="number"  id="loaded_weight"
         name="loaded_weight" min="35000" max="120000" maxlength="6" step="20"
         oncopy="return false" onpaste="return false">
   </div>
</fieldset>
<fieldset>
   <legend >net weight</legend>
   <div >
      <input type="number"  id="net_weight"
         name="net_weight" maxlength="5" step="20" oncopy="return false"
         onpaste="return false">
   </div>
</fieldset>

CodePudding user response:

Create yourself a custom validation rule using:

php artisan make:rule EqualToNetWeight

That will create a new Rule class named EqualToNetWieght at app/Rules:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EqualToNetWeight implements Rule
{
    private $loadedWeight;

    private $emptyWeight;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($loadedWeight, $emptyWeight)
    {
        $this->loadedWeight = $loadedWeight;
        $this->emptyWeight = $emptyWeight;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value == $this->loadedWeight - $this->emptyWeight;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The net weight does not equal the loaded weight minus the empty weight.';
    }
}

I've customised the messages() function to be more appropriate and descriptive for this use case.

The passes() function is where we perform the validation checking, in this case that your calculation (net weight == loaded weight - empty weight) passes and return the result (true or false) of that calculation.

The values of loaded weight and empty weight are accepted via the constructor() function.

To use the rule you would do something like:

'net_weight' => [
    'required',
    new EqualToNetWeight($request->loaded_weight, $request->empty_weight)
]
  • Related