HelpASisterOut
HelpASisterOut

Reputation: 3185

Validate input before Ajax Call

I have this pop up where a user enters his email:

<form class="form" id="PopupEmailForm">
            <div id="PopupEmail" class="modal fade" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-body">
                            <a data-dismiss="modal">Close</a>
                            <p>Enter The Email:</p>
                            <input type="email" id="EmailInput" name="Email" placeholder="[email protected]" required="required" />
                            <input type="submit" value="Send" id="PopupEmailSubmit" />
                        </div>
                    </div>
                </div>
            </div>
        </form>

On submit I am doing the following:

$('#PopupEmailSubmit').click(function () {

    $.ajax({
        type: "POST",
        url: "controller/action",
        data: {
            Email: $('#EmailInput').val()
        },
        beforeSend: function () {
            $("#PopupEmailSubmit").prop('disabled', true); 
            $.growl({
                title: "Email Confirmation",
                message: "Sending Email..."
            });
        },
        success: function (res) {
            if (res) {
                $.growl.notice({ title: "Email Confirmation", message: "Email Sent!" });
                $('#PopupEmail').modal('hide');
            } else {
                $.growl.error({ title: "Email Confirmation", message: "Email Not Sent. Try again later." });
            }
            $("#PopupEmailSubmit").prop('disabled', false); // enable button

        }
    });
});

I want to do a validation on the email input before I call the ajax post method.

And I want the validation to be similar(inline) to HTML5 validation for <input type="email"/>

Can anyone help

Upvotes: 1

Views: 445

Answers (2)

Ankit Khedekar
Ankit Khedekar

Reputation: 924

Since you are using a form, you could also do this in submit event of the form rather than click of the button

$('#PopupEmailForm').submit(function (event) {
  event.preventDefault();
  //ajax call here

});

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Try this:

$('#PopupEmailSubmit').click(function () {
    var email = $('#EmailInput').val();
    // create a validation rule
    if(validation successful)
    {
        // make ajax call
    }
    else
    {
        // show alert
    }
});

Upvotes: 0

Related Questions