Skip to content

Instantly share code, notes, and snippets.

@yaza-putu
Last active December 28, 2021 15:04
Show Gist options
  • Save yaza-putu/0e8c13100e1ef9f29306c8c4ef07d3c1 to your computer and use it in GitHub Desktop.
Save yaza-putu/0e8c13100e1ef9f29306c8c4ef07d3c1 to your computer and use it in GitHub Desktop.
Handel laravel validation with input error in javascript with ajax

required format data json to integrate function handleValidation() in helper.js like this

{
  "errors": {
    "nama": [
      [
        "Nama wajib diisi"
      ]
    ],
    "email": [
      [
        "Email wajib diisi"
      ]
    ],
    "alamat": [
      [
        "Alamat wajib diisi"
      ]
    ],
    "password": [
      [
        "Password wajib diisi"
      ]
    ],
    "password_confirmation": [
      [
        "Konfirmasi password wajib diisi"
      ]
    ]
  }
}

or if you use laravel you can follow instruction bellow

For Backend - Use it if implement validation in controler

  if($validator->fails())
  {
      return response()->json(['success' => false, 'messages' => $validator->errors()]);
  }

For Backend - Use it if implement validation in form request

 
  use Illuminate\Contracts\Validation\Validator;
  use Illuminate\Http\Exceptions\HttpResponseException;
  use Illuminate\Http\JsonResponse;
  use Illuminate\Validation\ValidationException;
  
  /**
   * Get the error messages for the defined validation rules.
   *
   * @return array
   */
  public function messages()
  {
      return [
          'title.required' => 'A title is required',
          'body.required' => 'A message is required',
      ];
  }
  
  /**
     * Handle a failed validation attempt with response json
     * in form request
     * @param  \Illuminate\Contracts\Validation\Validator $validator
     * @return json
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = (new ValidationException($validator))->errors();

        throw new HttpResponseException(
            response()->json(['errors' => $errors], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
        );
    }

in javascript

function handleValidation(messages)
{
    // reset before looping
    $('.invalid-feedback').remove();
    for(let i in messages)
    {
       for(let t in messages[i])
       {
          $('[name='+i+']').addClass('is-invalid').after('<div class="text-left invalid-feedback">'+messages[i][t]+'</div>');
       }
       
        // remove message if event key press
        $('[name='+i+']').keypress(function(){
            $('[name='+i+']').removeClass('is-invalid');
        });
        
        // remove message if event change
         $('[name='+i+']').change(function(){
            $('[name='+i+']').removeClass('is-invalid');
         });
    }
}
// you can use this to call this function
new handleValidation(messages)

in html

<form name="" id="" method="post" class="needs-validation">
<input type="text" name="address">
</form>

This function will find attribute name in input element and show the error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment