Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written:

<!doctype html>
<html lang="en">
<head>
<title>Testing form input</title>
<style type="text/css></style>
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<div id="form-wrapper">
<span id="error_box" style="display:none;"></span>
<form name="storyTeller" method="get" action="#" onSubmit="return validateForm()">
<p class="input-title">
<label for="title">TITLE:</label>
<input type="text" id="title" name="title" required onBlur="validateTitle(title)"/>
</p>
<textarea name="entry" id="entry" rows="10" cols="45" onBlur="validateEntry(entry)">
</textarea>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>

Validation rules in validation.js:

function validateTitle(title){/*validating title input*/
if (isNaN(document.getElementById('title').value)){
document.getElementById('title').style.background="#ccffcc";
document.getElementById('error_box').style.display="none";
return true;
}
else{
document.getElementById('error_box').innerHTML='Please enter a valid title';
document.getElementById('error_box').style.display="block";
document.getElementById('title').style.background="red";
return false;
}
}
function validateEntry(entry){/*validating text entry*/
var x=document.getElementById('entry').value;
x = x.trim();
if((x=="")||(x==null)){
document.getElementById('entry').style.background="red";
document.getElementById('error_box').innerHTML = 'Where is your story';
document.getElementById('error_box').style.display="block";
return false;
}
else{
document.getElementById('entry').style.background="#ccffcc";
document.getElementById('error_box').innerHTML='';
document.getELementById('error_box').style.display="none";
return true;
}
}
function validateForm(){/*overall form validation function*/
var error = 0;
if(!validateTitle('title')){
document.getElementById('error_box').style.display="block";
error++;
}
if(!validateEntry('entry')){
document.getElementById('error_box').style.display="block";
error++;
}
if(error > 0){
return false;
}
}

Answer №1

Transform the submit button into a regular button. Upon clicking it, trigger the final validation function which will manually submit the form if all conditions are met.

For instance:

<script>
function validateForm(){
    if(document.getElementById('textbox').value != "")
    document.getElementById('form').submit();
    else alert('Please fill out the text field');
}
</script>
<form id="form" action="#">
    <input type="text" id="textbox"/>
    <input type="button" id="button" value="Submit" onclick="validateForm()"/>
</form>

Answer №2

There seems to be a mistake in your script within the validateEntry() function.

Replace this line:

document.getELementById('error_box').style.display="none";

with this line:

document.getElementById('error_box').style.display="none";

Answer №3

After some modifications to your code, it now functions better for both submit and blur events.
To implement this in your HTML source, update both onblur attributes to onblur="validateEntry(this)". You can then utilize the following javascript:

function validateEntry(entry) { /*validation*/
    var error_box = document.getElementById('error_box');
    error_box.style.display = "none";
    if (entry.name == "title") { // INPUT type="text"
        if (!isNaN(entry.value)) {
            error_box.innerHTML = 'Please enter a valid title';
            error_box.style.display = "block";
            entry.style.background = "#fee";
            return false;
        } else {
            entry.style.background = "#ccffcc";
            return true;
        }
    } else if (entry.name == "entry") { // TEXTAREA
        var x = entry.value.trim();
        if ((x == "") || (x == null)) {
            error_box.innerHTML = 'Where is your story?';
            error_box.style.display = "block";
            entry.style.background = "#fee";
            return false;
        } else {
            entry.style.background = "#ccffcc";
            return true;
        }
    }
}

function validateForm() { /*form validation*/
    var form = document.forms['storyTeller'];
    var error_box = document.getElementById('error_box');
    var error = 0;
    var error_msg = '';
    if (!validateEntry(form['title'])) {
        error++;
        error_msg += error_box.innerHTML + '<br/>';
    }
    if (!validateEntry(form['entry'])) {
        error++;
        error_msg += error_box.innerHTML;
    }
    if (error > 0) {
        error_box.innerHTML = error_msg;
        error_box.style.display = "block";
        return false;
    } else {
        error_box.style.display = "none";
        return true;
    }
}

Check out the updated code on jsfiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to include additional details in a hyperlink so that clicking on it automatically populates the forms on the webpage?

Every day, I have to click on a link and input some information (username, password, code). Is there any way to modify the link so that it automatically fills in my account details when clicked? <input type="text" name="u" tabindex="1" size="15" id=usr ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

Tips for refreshing the 'state' of an Angular Router component

I'm facing an issue with passing data between pages using Angular routing. Everything works as expected when navigating to the "next" page for the first time. However, upon returning to the home page and selecting a different item, the Router's s ...

The image display feature in Django is currently not functioning

Recently, I returned to my Django project after being away for a few weeks due to a busy schedule. However, upon reopening the project today, I noticed that all the images were displaying with a little x sign or appearing broken in another browser. This is ...

Refreshing the page in VueJs does not trigger the axios function

I've encountered an issue with my VueJs app after purchasing the Vuexy template from ThemeForest. I created a new component called CountryTable.vue, and while it works initially, it fails to display data when I refresh the page. It only shows data whe ...

How can I collect various values from input fields that are within a foreach loop using jQuery?

<script> $("#submit").click(function(e){ e.preventDefault(); subjectID = $("#subjectID").val(); subject = $("#subject_"+subjectID).val(); subject_code = $("#subject_code_"+subjectID).val(); internal_marks = ...

Interactive SVG viewport dimension

Check out my "hamburger button" made in SVG, shown below. body { margin: 0; text-align: center; } svg#ham-btn { margin: 2rem; border: 1px solid black; fill: #383838; } <svg id="ham-btn" width="107.5px" height="80px" viewBox="0 0 80 80" pre ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

VueTablePlus dropdown filter options for Vue.js version 2

I am facing an issue with populating dropdown options on vue good table. My approach involves making an API call to fetch the possible values for the dropdown and then assigning them to the column filter. However, I am struggling to make it work. <vue ...

Transferring live data between AJAX-triggered pop-up windows

Utilizing modals frequently in my application is a common practice. There are instances where I need to transfer data from one modal box to another. For instance: Suppose there is a table listing different car manufacturers (Audi, BMW, Honda, etc). Each r ...

Can responsive images be utilized with a DIV's background-image property?

For my website, I want to incorporate a variety of Thumbnails that are retrieved from a database and displayed in different sizes within a Masonry grid. Typically, I would use background-image:url(image.jpg); background-size: 100% 100%:, but I am aiming t ...

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

What is the reason behind jQuery's .html("abc") only providing temporary insertion?

I have come across an issue with an HTML button that triggers a function. Whenever the button is clicked, a div is inserted but it only appears for a brief moment before disappearing both visually and in the HTML tree. function openBox () { $( '#0&a ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

convert a JSON object to an array using jQuery

Can anyone help me with converting an object into an array using jQuery? [["20"],["30"],["45"],["54"],["33"],["15"],["54"],["41"]] I am looking to achieve an array output like this: [20,30,45,54,33,15,54,41] Any suggestions on how to accomplish this? ...

The background of the section does not extend to the full height

Currently, I am using the <section> tag as a background for a specific section on my website. However, I am facing an issue where the height of the background is being cut off, even though the content continues below it. I have attempted various pos ...

Having trouble applying CSS while printing using the ngx-print library in Angular 14. Can anyone help me out with this issue

The table shown in the image is experiencing issues with applying CSS properties when printing. While the background graphics feature has been enabled, the preview section still does not reflect the CSS styling. What could be causing this discrepancy? Cli ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...