1

I've a register form in my project and I'm validating it on server side. If any of the fields is empty, it shows validation errors defined in Register Controller. The issue is that If the end-user again hits submit, the same error is duplicated that looks weird. How would I solve it?

Register Blade

    <form id="register_forms" style="display:none" action="{{route('register' , app()->getLocale())}}">
      @csrf
       <div>
        <label for="register_name"></label>
          <input placeholder="name" id="register_name" type="text" class="form-control input @error('register_name') is-invalid @enderror" name="register_name" value="{{ old('register_name') }}" required autocomplete="register_name" autofocus/>
    
          @error('register_name')
           <span class="invalid-feedback" role="alert"><strong>{{ $message }}</strong></span>
          @enderror
       </div>
    
    
       <div>
        <label for="register_email"></label>
         <input placeholder="email" id="register_email" type="email" class=" input form-control @error('register_email') is-invalid @enderror" name="register_email" value="{{ old('register_email') }}" required autocomplete="register_email"/>
    
          @error('register_email')
           <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong></span>
          @enderror
       </div>


  <div class="some-class">
   <input  id="user_type_private" value="user" type="radio" class="radio" name="user_type" >
   <label  for="user_type_private">private</label>
    <input id="user_type_company" value="company" type="radio" class="radio" name="user_type" >
    
   <label  for="user_type_company">{{ __('Company')}}</label>
      @error('user_type')
       <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong></span>
      @enderror

    </div>
    
       <input id="my-register" type="submit" value="submit">
    
     </form>

JavaScript

<script>
  $("#my-register").click(function(e){
     e.preventDefault();
     $.ajaxSetup({
     headers: {
                   'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
               }
           });
            $.ajax({
        type: "post",
      url: "{{ route('register') }}",
      data: $('#register_forms').serialize(),
      dataType: 'json',
      success: function(data) {
            window.location = "https://carchainclassics.com/login";
        },
        error: function (err) {
            if (err.status == 422) {
                console.log(err.responseJSON);
                $('#success_message').fadeIn().html(err.responseJSON.message);

                $.each(err.responseJSON.errors, function (i, error) {
                    grecaptcha.reset();
                    var el = $(document).find('[name="'+i+'"]');
                    el.after($('<span style="color: #ff0000;">'+error[0]+'</span>'));
                });
            }
        }
    });
        });
</script>

Controller

protected function validator(array $data)
{
    $validator = Validator::make($data, [
        'register_name' => ['required', 'string', 'max:35'],
        'register_email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
         'user_type' => ['required',Rule::in(['user', 'company']),],
    ]);
    $validator->setAttributeNames([
        'register_email' => 'email'
    ]);

    return $validator;
}
2
  • 1
    You are appending (el.after), meaning you'll add a new copy every time. Maybe you should instead create an element to hold the error message (which will be empty at the beginning), whose content you can replace after every submit. Commented Mar 23, 2021 at 11:44
  • Following on the comment of @El_Vanja You can also change the visibility of the error message. Commented Mar 23, 2021 at 20:54

1 Answer 1

1

You just need to empty the html before each request. Add below code in your jquery ajax for clearing message. Add a class of message to each message span.

beforeSend: function(data) {
            window.location = "https://carchainclassics.com/login";
    $('.message').empty();
},

error: function (err) {
    if (err.status == 422) {
    console.log(err.responseJSON);
                    
    $('#success_message').fadeIn().html(err.responseJSON.message);

    $.each(err.responseJSON.errors, function (i, error) {
            grecaptcha.reset();
            var el = $(document).find('[name="'+i+'"]');
            el.after($('<span class="message" style="color: #ff0000;">'+error[0]+'</span>'));
        });
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It worked for me but one last thing left. I just added the radio buttons to select the user_type and add validation into controller but it shows two validation errors on click submit button. Could you please re-check my question above and suggest what I' m doing wrong?
The error is "user field is required" but it appears twice not a single time, don't know why..
Are you sure? You don't have any validation for user field.

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.