Friday, 13 September 2013

Cancelling form submission through JavaScript

When doing client-side validation on a web form, there arises a need to cancel the form submission if the user has not provided the data as required by the host website. This can be easily accomplished by invoking the preventDefault method on the 'event' argument passed to the form's 'Submit' event-handler. An example will better illustrate it; so, here it goes:

<!DOCTYPE html>

<html lang="en">
<meta charset="utf-8">
<title>Cancelling Form Submission</title>
    .error {border: 2px solid red;}
    div:last-child {margin-top: 10px;}

<form method="post" action="#">
        <label for="name">Your name (atleast 3 characters long): </label>
        <input type="text" name="name" id="name" required />
        <button type="submit">OK</button>

    var formElement = document.forms[0];
    formElement.addEventListener("submit", onFormSubmission, false);
    function onFormSubmission(e) {
        var textElement = document.getElementById("name");
        if (textElement.value.length < 3) {
            textElement.className = "error";



Some people could say that what I have written is nothing new, and is known for ages. They would be very true if they said so. However, my motive behind writing these posts is not to announce any path-breaking discoveries to the world, but to note down some of my learnings so as to reinforce it.

No comments:

Post a Comment