Ad

Input Value Must Be Equal To Some Value In Database

- 1 answer

So i have this simple code to select value from database in registration form and it's work great

<div id="ref1" class="form-group form-material floating">
    <select class="form-control" name="reference" id="reference">
      @foreach (App\Models\Reference::getReference() as $key => $value)
        <option value="" selected disabled hidden></option>
        <option value="{{$value->id}}">{{$value->reference}}</option>
      @endforeach
    </select>
    <label class="floating-label" for="inputStatus">Reference</label>
</div>

But i want to change this into input field, so when user type it manually and it's not having the same value in the database, the registration will fail (Error Message : 'Wrong reference code'), does anyone have and idea how to do it? Thanks

Edit 1 : I also have this validation code for the reference

reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Reference maximal 8 digit'
                }
            }
        }

Can i also use exists rule on that validator?

Ad

Answer

This can be done by creating custom Laravel Request validation. If your reference is stored in database, you can check if the input value exists in database, after the form is submitted by using exists rule. Here's a simple example:

    public function rules()
    {
        return [
            'field_name' => 'exists:your_table_name', //Table name where reference is stored
        ];
    }
    public function messages()
    {
        return [
            'field_name.exists' => 'Wrong reference code',
        ];
    }

You can read more on official documentation.

Ad
source: stackoverflow.com
Ad