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

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

The principle of event delegation in jQuery

Are event handlers delegated across both <div> tags? In other words, is there one or two event handlers being used? I'm looking to extract the data-id from the event.delegateTarget. It's straightforward when attached to each of the <div& ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Is there a way to verify if a username is available in the database?

Is there a way to check if the username entered in an input text field is available based on the database using JSF2? ...

Setting up grunt-contrib-nodeunit to generate JUnit XML output: a step-by-step guide

I have been searching for information on how to configure reporters in the grunt-contrib-nodeunit module, as I recently added this task to my Gruntfile.js. nodeunit: { all: ['nodeunit/**/*.test.js'], } Does anyone know how to instruct Grunt ...

Run the GetServerSideProps function every time the button is clicked

Struggling with my NextJS app development, I encountered an issue while trying to fetch new content from an API upon clicking a button. The server call is successful, but the update only happens when I refresh the page rather than triggering it with the bu ...

What is the best way to restructure this deeply nested JSON information?

I'm working with the payload structure of my API and I want to format the data in a way that allows for dynamic display on the frontend without hardcoding column names. Currently, I am using DRF, axios, and react-redux, but I feel like I may need to d ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

A pop-up window displaying an electron error message appears, but no errors are logged in the console

In a Nutshell: While developing a single-page website with Electron, I encountered the common issue of jQuery not being globally accessible. To tackle this problem, I decided to simplify it by using a quick start example, but unfortunately, I'm strugg ...

Is there a Joomla extension available that can display or conceal content upon clicking?

Looking to enhance my Joomla site by installing a plugin that allows me to toggle the visibility of content with a click, similar to how FAQ sections work on many websites. Question 1 (click here for the answer) { Details for question 1 go here } Questi ...

Accessing variables in AngularJS from one function to another function

I am facing an issue where I need to access a variable in one function from another function. My code structure is as follows: NOTE: The value for submitData.alcohol is obtained from elsewhere in my code. angular.module('app',['ui.router&a ...

Tips for avoiding an automatic slide up in a CSS menu

Is there a way to disable the automatic slide-up effect on my CSS menu when clicking a list item? I have tried using stop().slideup() function in my JavaScript code, but it doesn't seem to work. Additionally, I would like to highlight the selected lis ...

Having issues with the link page in react-router-dom?

Currently, I am utilizing the react-router-dom library to manage routers. However, I have encountered an issue where linking to another page does not change the page, but instead adds the new page right after the previous one as shown in the image below. W ...

Vuejs - Expanding Panels

Trying to implement an accordion using Vue.js has been a bit challenging for me. While I came across some examples online, my requirements are slightly different. In order to maintain SEO compatibility, I need to use "is" and "inline-template", which make ...

Adjustable height and maximum height with overflow functionality

Currently, I am in the process of developing a task manager for my application and facing an obstacle when trying to calculate the height of a widget. My goal is to determine the maximum height (assuming a minimum height is already set) by subtracting a ce ...

Is there a way to shorten the length by left-clicking and increase it by right-clicking?

Illustration: section.my{margin: 20px;} <section class="my"></section> Hover over: section{padding: 10px;} Double click: section{border: 1px solid black;} ...

Utilize AJAX and jQuery to seamlessly submit a form

I am attempting to use jQuery and AJAX to submit a form in order to add a row to a table called cadreSante (which is in French). The code I am using for this operation is provided below. Can someone please identify any errors in the code and suggest ways t ...

The event listener for the hardware back button in $ionicPlatform is being triggered repeatedly

Encountering a glitch with the back button being triggered multiple times. While I'm in the "messages" $state, everything functions normally when hitting the back button. var messageIsClosed = true; $ionicPlatform.onHardwareBackButton(function(even ...