Laravel 5 Validation - error class on form elements

19,183

Solution 1

This was the correct answer for me, without using additional div's :

{!! Form::email('email', null, $attributes = $errors->has('email') ? array('placeholder' => 'Email', 'class' => 'form-control has-error') : array('placeholder' => 'Email', 'class' => 'form-control')) !!} 
{{$errors->first('email')}}

Solution 2

You can use if condition for check errors:

 <div class="form-group {{ $errors->has('email') ? 'has-error' :'' }}">
   {!! Form::text('email',null,['class'=>'form-control','placeholder'=>'Email Address']) !!}
   {!! $errors->first('email','<span class="help-block">:message</span>') !!}
</div>

Solution 3

You could just add HTML around it and style it however you want.

HTML:

<span class="error">{{$errors->first('email')}}</span>

CSS:

.error {
    border: 1px solid red;
}

Edit: Add the has-error class to the input itself like this:

{!! Form::email('email', null, array('placeholder' => 'Email', 'class' => 'form-control ' . $errors->first('email', 'has-error'))) !!}
Share:
19,183
paulalexandru
Author by

paulalexandru

http://www.idealhost.ro Nothing else matters.

Updated on June 04, 2022

Comments

  • paulalexandru
    paulalexandru almost 2 years

    My validation form works fine and it looks like this:

    {!! Form::email('email', null, array('placeholder' => 'Email', 'class' => 'form-control ')) !!}
    {{$errors->first('email')}}
    

    If the email is not good, I get this error: The a email has already been taken.

    The thing is that I wan't to put a css class on the input also like error in order to add a red background border to the input.

    How can I do this?

  • paulalexandru
    paulalexandru over 8 years
    I dont need a custom error message. I need a css class added to my input.
  • paulalexandru
    paulalexandru over 8 years
    I don't need a new element created. I need a css class added to my email input.
  • paulalexandru
    paulalexandru over 8 years
    That class should appear only if the form validation failed, not always as you sugested.
  • Thomas Kim
    Thomas Kim over 8 years
    There's a very simple solution to that. :) Check my edit.
  • Dev
    Dev over 7 years
    The problem on this one is Input does not take .has-error class in Bootstrap. This needs to be applied from parent div. Otherwise, this was a good solution.
  • kapitan
    kapitan about 2 years
    i only need to add a class for my input fields to have a red border and this solution worked for me, it is a very long approach though.
  • kapitan
    kapitan about 2 years
    i deleted the $attributes = and it worked the same.