L
L
lolrofl012018-07-27 19:53:49
Laravel
lolrofl01, 2018-07-27 19:53:49

How in laravel, when an error occurs in form validation, to visually show which field has an error?

SUBJECT. After submitting the form, the information gets into the validator. If the validator finds an error, it will redirect back to the form with an array of errors. In general, this is all the documentation describes in detail how to display these errors and so on. I'm interested in something else - how to highlight fields with an error, and, preferably, indicate the error itself under each field?
I managed to do this using all the constructions from the documentation, but the code turned out, to put it mildly, poorly readable. I'm sure there is a way to make it easier. Here is the code:

<input class="form-control" name="inn" type="text" value="{{ old('inn') }}">
                                    <div class="div_error">
                                        {{ $errors->first('inn') }}
                                        @if( session('bad_inn') == 1 )
                                            Неправильное ИНН
                                        @endif
                                    </div>

The bottom line is this: there is a regular text field for entering a TIN. The field passes the validator, if there is an error in this field, then it will be written to the div with the errors class. Next, I check on js if the error div is not empty, then I color the adjacent field with red. And the second bad_inn error is already my experience, I check after the validator for my TIN database, if I don’t find the entered one, then I display an error.
I am sure that what I have done is fundamentally wrong, although it works, and it is possible to somehow implement this idea much easier. And how to highlight the field, and how to add your own mistakes in a different way than mine. Especially if the form consists of 20+ fields, it is physically very dreary to write.
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-07-27
@lolrofl01

Typical bootstrap construction:

<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
  <input id="password" placeholder="Пароль" type="password" class="form-control" name="password" required>
  @if ($errors->has('password'))
    <span class="help-block">
      <strong>{{ $errors->first('password') }}</strong>
    </span>
  @endif
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question