Lukasz
Lukasz

Reputation: 409

Prevent user to send empty fields

My jQuery validation form warns user if he tries to send empty data if he clicks "Next" button.

Anyway, user still able to send empty data by pressing Enter.

So I used code below, it makes pressing Enter same with clicking "Next" button;

// this script makes pressing Enter gives error. But empty data still goes to database.
   $('.form-horizontal').keypress(function (event) {
        if (event.which === 13) {
        $(".next").trigger('click');
        }
        });

This code only prevents user to go next step. But when user hits the Enter data being written to database even though he sees "Error Message".

*

Well, server-side verification prevents that easily. But why it's necessary keep server busy with that if we can prevent earlier?

Here is JsFiddle you can test the whole thing:

http://jsfiddle.net/6zu2vsj7/3/

*

Is there any way to make it work without keeping servers busy with empty fields? And I don't want to prevent user pressing Enter because this is not cool at all and not good for user experience.

Upvotes: 1

Views: 175

Answers (3)

Murali Mohan
Murali Mohan

Reputation: 136

You can add a condition to check whether the form is valid or not before you sending the data to server as below. hope this helps...

// Let's act like we send to database.
            $(function(){
                $('input[type=submit]').click(function(){
                    if($("#myform").valid()){

                    $.ajax({
                        type: "POST",
                        url: "sent.php",
                        data: $("#myform").serialize(),
                        beforeSend: function(){
                            $('#stepsuccess').html('Sent to the database. Strange.');               
                        },
                        success: function(data){
                            $('#stepsuccess').html(data);

                        }
                    });
                    }
                });
            });

Upvotes: 2

mR.aTA
mR.aTA

Reputation: 314

Try this:

$(".form-horizontal").submit(function(e){
//do somethings or other validations
return false;
});

well! server side validation is necessary because client side validation is just for normal users! not hackers and robots! got it?! in fact client side validation can be easily pass.

Upvotes: 0

Mohamed Badr
Mohamed Badr

Reputation: 2642

You just need to prevent the default behavior for that event

you can use this

 $('.form-horizontal').keypress(function (event) {
            if (event.which === 13) {
                event.preventDefault();
                $(".next").trigger('click');
            }
        });

Upvotes: 1

Related Questions