Sun's avatar
Level 1

Required HTML Validation not working

Hi guys, I am new to Ajax. I just created an edit modal and realized the ``required`' validation from HTML5 is not working.

Edit Modal

<div id="editModal" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form">
                        @csrf

                        <input id="id_edit" type="text" class="form-control" name="id_edit" hidden>

                        <div class="form-group row">
                            <label for="first_name_edit" class="col-md-4 col-form-label text-md-right">First Name</label>
                            <div class="col-md-6">
                                <input id="first_name_edit" type="text" class="form-control" name="first_name_edit" required>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="last_name_edit" class="col-md-4 col-form-label text-md-right">Last Name</label>
                            <div class="col-md-6">
                                <input id="last_name_edit" type="text" class="form-control" name="last_name_edit" required>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="email_edit" class="col-md-4 col-form-label text-md-right">Email</label>
                            <div class="col-md-6">
                                <input id="email_edit" type="email" class="form-control" name="email_edit" required>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="user_role_edit" class="col-md-4 col-form-label text-md-right">User Role</label>
                            <div class="col-md-6">
                                {!! Form::select('user_role_edit', $roles->all(), null, ['class'=>'form-control', 'id' => 'user_role_edit', 'required']) !!}
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="user_status_edit" class="col-md-4 col-form-label text-md-right">User Status</label>
                            <div class="col-md-6">
                                {!! Form::select('user_status_edit', $status->all(), null, ['class'=>'form-control', 'id' => 'user_status_edit', 'required']) !!}
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button value="submit" class="btn btn-primary edit" data-dismiss="modal">{{ __('Update') }}</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

Javascript

//edit form
        $(document).on('click', '.edit-modal', function() {
            $('.modal-title').text('Edit User');
            $('#id_edit').val($(this).data('id'));
            $('#first_name_edit').val($(this).data('first_name'));
            $('#last_name_edit').val($(this).data('last_name'));
            $('#email_edit').val($(this).data('email'));
            $('#user_role_edit').val($(this).data('role_id'));
            $('#user_status_edit').val($(this).data('status_id'));
            id = $('#id_edit').val();
            $('#editModal').modal('show');
        });

        $('.modal-footer').on('click', '.edit', function() {
            $.ajax({
                type: 'PUT',
                url: '/rainman-users/' + id + '/update',
                dataType: 'json',
                data: {
                    '_token': $('input[name=_token]').val(),
                    'id': $("#id_edit").val(),
                    'first_name': $("#first_name_edit").val(),
                    'last_name': $("#last_name_edit").val(),
                    'email': $("#email_edit").val(),
                    'role_id': $("#user_role_edit").val(),
                    'status_id': $("#user_status_edit").val()
                },
                success: function(data) {
                    console.log(data);
                    window.location.reload();
                }
            });
        });
0 likes
16 replies
Sun's avatar
Level 1

FYI, I have two modal forms on this page. The add modal is working fine with the validation, but the edit modal is not.

Cronix's avatar

I wish people would stop using that dumb form library. There's a reason why laravel removed it from the core... This is dead simple with regular html.

I don't use that library, but try setting a key AND value for requiredjust like you are with all of the other attributes, like

{!! Form::select('user_status_edit', $status->all(), null, ['class'=>'form-control', 'id' => 'user_status_edit', 'required' => 'required']) !!}

It might be 'required' => 'required' or it might be 'required' => true. Not sure with that library...

2 likes
lostdreamer_nl's avatar
Level 53

I'm assuming that the first two hardcoded input fields also dont work with their required fields?

<input id="first_name_edit" type="text" class="form-control" name="first_name_edit" required>

<input id="last_name_edit" type="text" class="form-control" name="last_name_edit" required>

It's because you're not using the actual form submition mechanism of the form, but ajax in the background.

If you're using ajax, then you should check those fields yourself.

Something like this:

var required = $('input,textarea,select').filter('[required]:empty');
if(required.size() > 0) {
    // not all required fields are filled in
}

Actually, thinking about it, with MSIE this will probably do both the ajax submittion, AND submit a GET request to the same URL as this form is being shown on (MSIE has the nasty habit to think of a <button> as a submit button if there is no actual submit button in the form.

Sun's avatar
Level 1

@Cronix The select options are okay. My first_name, last_name, and email inputs are set as required, but when I submit the form with empty value, it doesn't show the validation .

Cronix's avatar

Then see @lostdreamer_nl answer. html required fields only work if submitting a regular html form. You'll have to create your own for things that are submitted via ajax since you prevent the default form behavior.

And this

window.location.reload();

is not the right thing to do in your success event. You should render just the additional data/altered data/removed data on the page instead of reloading the whole page. This defeats the entire point of using ajax, so you really might as well not even use ajax here.

The proper thing to do is only update the current page with the new data, not reload everything. That's a complete waste and actually puts more load on the server than if you just didn't use ajax.

Sun's avatar
Level 1

@lostdreamer_nl @Cronix Thank you! Sorry I am really bad with JavaScript. I got "Uncaught TypeError: required.size is not a function". Could you please show me a complete example? I checked other examples, but the format is different than yours.

Snapey's avatar

I am really bad with JavaScript

why t f are you doing it this way then?

Just post the form as normal

1 like
Sun's avatar
Level 1

@Snapey Well, it's because I have done it in the normal way like a hundred times. Time to learn some new tricks.

Sun's avatar
Level 1

@Cronix Do you think I should use Vue JS? I played around with that, very cool, but my application is not a real-time application. All I want from Ajax is the one page CRUD features that will provide a better User Experience.

Snapey's avatar

well as cronix said, submitting the form, getting the response and then doing window.location.reload is the wrong trick to be learning

As you have also found, evaluation of required field is only performed on form submit

Cronix's avatar

Good thing to learn, isn't it?

Sure, if you're learning how to do it properly.

Sun's avatar
Level 1

@Cronix I was pointing to the advice you just mentioned, lol

Sun's avatar
Level 1

@Cronix I found a couple options, I will give them a try, then show you to see whether they are the right method to implement. Then I will close this question. Thank you very much!

Cronix's avatar

As for the original problem, try using length instead of size(). size() was deprecated.

if(required.length > 0) {
    // not all required fields are filled in
}

Please or to participate in this conversation.