gymcode
gymcode

Reputation: 4623

HTML Form Check Empty Fields

I have implemented input validation in my HTML form. However, it does not prompt the user in case of any errors and still proceeds to send its data to the test server.

Below is my code:

<html>
<head>
    <style>
        input {margin: 10px 5px 10px 5px;}
        select {margin: 10px 5px 10px 5px;}
    </style>
    <script language="JavaScript">
    function validate(form1)
    { if (form1.name.value == "" || form1.surname.value == "" || form1.email.value == "" || form1.dob.value == "")
        { alert("One of the field is empty.")
            form1.firstname.focus()
            form1.firstname.select()
            form1.lastname.focus()
            form1.lastname.select()
            form1.email.focus()
            form1.email.select()
            form1.dob.focus()
            form1.dob.select()

            return false
        }
    return true}
    </script>

</head>
<body>
    <form method="GET" action="http://www.test/cgi-bin/reply.pl"
    onSubmit="return validate(this)">
        First Name<input type="text" name="firstname"><br>
        Last Name<input type="text" name="lastname"><br>
        Email Address<input type="email" name="email"><br>
        Date of Birth<input type="date" name="dob"><br>
        Favourite Sport
        <select name="sports"><br>
        <option value="athletics">Athletics</option><br>
        <option value="basketball">Basketball</option><br>
        <option value="cricket">Cricket</option><br>
        <option value="football">Football</option><br>
        <option value="hockey">Hockey</option><br>
        <option value="swimming">Swimming</option><br>
        <option value="tennis">Tennis</option><br>
        </select><br>
        <input type="Submit"> <input type="reset">
    </form>

</body>

</html>

Upvotes: 4

Views: 13124

Answers (2)

sahilkmr78
sahilkmr78

Reputation: 184

The problem is that when you use onsubmit, your code won't call your function until submission. One way to deal with a user submitting a form with a required input blank is using the required element:

<form>
First Name<input type="text" name="firstname" required><br>
<input type="Submit"> <input type="reset">
</form>

https://jsfiddle.net/d43rLno5/

Upvotes: 11

yosefrow
yosefrow

Reputation: 2268

onSubmit happens when you submit the form as far as I understand so to make it fire before you need to use onclick and onkeyup for enter key to include the key event

Trigger a button click with JavaScript on the Enter key in a text box

Form 'onsubmit' not getting called

Otherwise you need to stop the default event from happening if you don't want the form action to be called right away

You can stop the default event with

if (event.preventDefault) {
    event.preventDefault(); 
} else { 
    event.returnValue = false; 
} 

Then you can use jquery .post method to send an Ajax query to your script

Upvotes: 0

Related Questions