1

I want to give an error message if a string is entered in a integer inputfield with an multidimensional array.

View:

<div class="col-md-8">
     <input name="answer[sleep][score]" type="text" class="form-control @error('answer[sleep][score]') @enderror" placeholder="Score" value="{{ @$answer_array['sleep']['score'] }}">
     @error('answer[sleep][score]')
     <span class="invalid-feedback" role="alert">
         <strong>Geen letters alsjeblieft.😉</strong>
     </span>
     @enderror
     </div>

Controller:

        $request->validate([
            'answer.sleep.score' => 'nullable|numeric',
        ]);

when i click save it just refreshes the page and does nothing. Can anybody please help me, how do i show the error on a multidimensional array.

Thanks!

2 Answers 2

2

@error is a blade directive used to display error messages in your template. The right way to use it is:

@error('answer.sleep.score')
  <div>{{ $message }}</div>
@enderror

Notice that in order to detect whether the error message exists, I'm using the same format as you did in the validation i.e. answer.sleep.score and NOT answer[sleep][score].

If you want to add a class to your input element when an error is detected you can do this:

<input name="answer[sleep][score]" type="text" class="form-control {{ $errors->has('answer.sleep.score') ? 'error-class' : '' }}" placeholder="Score" value="{{ old('answer.sleep.score') }}">

By using old, you can pre-fill input field with the posted value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried the dot's, but it didn't work. Apperently i put the wrong $error in my class. It seemed to work on every other page the way i did it, but not with this type array. I modified it a little bit to my linking, but this is definitively the solution. Thanks!
0

You can use regular expression for the validation will be much better then this:

$request->validate([
   'answer.sleep.score' => 'nullable|regex:/^[0-9]*$/',
]);

This allow you to enter only numbers in the field.

3 Comments

Sorry, i tried this, but this doesn't work. I get the same result. Page just refreshes. :(
How's that much better? According to docs, if you specify numeric as a rule, the field under validation must be numeric.
Are you facing issue with how to display error message for the validation in blade file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.