简体   繁体   中英

Need to validate form before sending

I am trying to send a form to email but I wanted the name field to be validated (if no content then don't send) I cannot get it validate and then end through the php script I have working correctly I have created a jsfiddle at the following link Can someone help please?

$(document).ready(function () {
$('.form-horizontal').on('submit', function (e) {

    e.preventDefault();
    var name = $('#name').val();
    if (!name) {
        showError();
    }
    else {
        $('#contact-form').submit();
    }

});

function showError() {

    $('.tyler-error').show();
}

});

Working fiddle

In your fiddle, you didn't select jQuery from the library dropdown.

Secondly, you should avoid submitting the form from within the submit handler, instead just preventDefault if there is a validation error.

$('.form-horizontal').on('submit', function (e) {
    var name = $('#name').val();
    if (!name) {
        showError();
        e.preventDefault();
    }
});

If you really want to keep the code as it was, you need to call the forms submit function, not the jQuery submit function:

$('#contact-form')[0].submit();
// or
$('#contact-form').get(0).submit();

Here, [0] or .get(0) is giving you the plain JavaScript DOM element with no jQuery wrapper, and with this you can call submit() .

HTML5 provides input validation, you can set in order to tell the browser that your html view is HTML5.

//Set your doctype for HTML5.
<!doctype html>
<html>
<head>
    <title></title>
</head>
<body>
    <form id="the_form">
        //here html5 will not submit if the box is empty or does not meet the email
        //addres format.
        <input type="email" name="email" id="email" placeholder="Enter email..">
        <input type="submit" value="send">
    </form>
</body>
</html>

If you dont want to use HTML5, you could also make a simple javascript code to not submit if the input is empty.

<html>
<head>
    <title></title>
    <script type="text/javascript">
    window.onload = init();

    function init(){
        //get form.
        var form = document.getElementById("the_form");

        form.onsubmit = email_validation;
    }

    function email_validation(){
        email = document.getElementById("email");

        if(email.value == ''){
            //return false to avoid submission.

            return false;
        }
        else{
            //do whatever code.
        }
    }
    </script>
</head>
<body>
    <form id="the_form">
        <input type="text" name="email" id="email" placeholder="Enter email..">
        <input type="submit" value="send">
    </form>
</body>
</html>

with this way, your email will be validated before is sent, hope this work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM