How can I showcase JavaScript validation messages on the screen instead of using alert messages?

In my project using struts 1.3.8, I've implemented the Struts ValidatorPlugIn to handle both client-side and server-side validation messages.
Currently, the client-side JavaScript is generated by the validator plugin, which displays any validation errors in alert messages. However, I now need to display these error messages next to the respective text fields instead.
Up until now, I have only worked with alert messages for displaying errors. How can I adjust the functionality to meet this new requirement?
Here is the code snippet generated by the plugin:

function jcv_handleErrors(messages, focusField) {
    if (focusField && focusField != null) {
        var doFocus = true;
        if (focusField.disabled || focusField.type == 'hidden') {
            doFocus = false;
        }
        if (doFocus && 
            focusField.style && 
            focusField.style.visibility &&
            focusField.style.visibility == 'hidden') {
            doFocus = false;
        }
        if (doFocus) {
            focusField.focus();
        }
    }
    alert(messages.join('\n'));
}

Answer №1

In the absence of specific details, my suggestion is to modify your code as follows:

window.alert = function(message){
    console.log(message);
}

You can test this out on JS Fiddle here.

This alteration redirects any alerts from alert() to console.log() instead.

If you prefer to direct the messages to a specific element instead, you can use the following approach:

window.alert = function(message) {
    var output = document.getElementById('output'),
        newTextContainer = document.createElement('p'),
        text = document.createTextNode(message);
    newTextContainer.appendChild(text);
    output.appendChild(newTextContainer);
}

Test it out on JS Fiddle here.

Note that using either method will disrupt any existing alert() functionality on your page. I recommend creating a new function based on the latter example and calling that rather than replacing alert() directly.

To create a custom alert function that allows you to specify an element for displaying alerts:

function newAlert(message, elem) {
    var output = elem ? document.getElementById(elem) : document.getElementById('output'),
        newTextContainer = document.createElement('p'),
        text = document.createTextNode(message);
    newTextContainer.appendChild(text);
    output.appendChild(newTextContainer);
}

View the demo on JS Fiddle here.


Edit: In response to the query from the original poster below:

After submitting the form again, I want to replace the previous error message. I don't want to display the same message twice.

If you only wish to show the latest error message and overwrite any previous ones, you can achieve this with the following methods. The first example uses a while loop to remove the current message in the output element before appending the new error message:

function newAlert(message, elem) {
    var output = elem ? document.getElementById(elem) : document.getElementById('output'),
        newTextContainer = document.createElement('p'),
        text = document.createTextNode(message);
    while (output.firstChild){
        output.removeChild(output.firstChild);
    }
    newTextContainer.appendChild(text);
    output.appendChild(newTextContainer);
}

Try it out on JS Fiddle here.

Alternatively, you can simply update the content of the first paragraph element within the output container if it exists, or create one to display the new message:

function newAlert(message, elem) {
    var output = elem ? document.getElementById(elem) : document.getElementById('output'),
        textContainer = output.getElementsByTagName('p')[0] || output.appendChild(document.createElement('p'));

    if (textContainer.firstChild){
        textContainer
            .firstChild
            .nodeValue == message;
    }
    else {
        textContainer
            .appendChild(document
                         .createTextNode(message));
    }
}

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

Utilizing the index of a generic type within TypeScript

I am attempting to design generic message types that become increasingly specific, with the most precise type being inferred during the function call or class creation. Consider the following code snippet: type MessageHeaderType = 'REQUEST'|&apo ...

Different width, same height - images arranged side by side in a responsive layout

The problem lies in the images: https://i.sstatic.net/rydNO.png Here is an example of desktop resolution: https://i.sstatic.net/uv6KT.png I need to use default size pictures (800x450px) on the server. This means I have to resize and crop them with CSS to ...

Employing selenium.isElementPresent in Selenium 1 does not have the capability to identify an element that is dynamically added to the Document Object Model (

After trying out various locators, I have yet to find one that can detect an element that was added to the DOM. Below is my latest attempt at solving this issue: selenium.fireEvent("//button[2]", "click"); waitUntil(new Condition() { @Override pu ...

Is there a way to generate a fresh array by filtering an array of objects based on a single value?

I am currently working with an array of objects: const dummyLinkRows = [ { id: 'entity:link/1:en', categories: [ { name: 'Human Resources' }, { name: 'Social' } ], nam ...

The issue with ng-repeat causing incorrect image width in Flexslider

My webpage features image scrolling functionality, powered by Flexslider. The images on the page are sorted by date - for example, selecting "last 7 days" will display images from the past week (data managed through AngularJS). However, when the JSON dat ...

Guide to generating a PDF file and utilizing a Node.js program for the download process

Seeking assistance in creating a button using my Node.js application to generate a downloadable PDF file filled with information from a PostgreSQL database. Any help is greatly appreciated! ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

What is the best way to enhance a React Native component's properties with Flow?

I'm currently working with Flow version 0.54.1 in my React Native project, specifically using version 0.48.3. I have developed a component named PrimaryButton that acts as a wrapper for the native TouchableOpacity component. My goal is to define custo ...

Why won't my JavaScript addEventListener activate on form submission?

I have a basic question as a beginner in JavaScript. I am facing some challenges with my first task involving JavaScript. I decided to learn JS by creating a TODO List, but I am stuck right at the beginning. The event listener that should respond when the ...

"Maximizing Efficiency: Chaining Several Actions Using the JavaScript Ternary Operator

When the condition is true, how can I chain two operations together? a = 96 c = 0 a > 50 ? c += 1 && console.log('passed') : console.log('try more') I attempted chaining with && and it successfully worked in react, b ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

What is the best way to create a Snap.svg map using AngularJS?

I am in the process of creating a web interface for an online board game. My goal is to load a Snap.svg map using Snap.load asynchronously. Once the map is loaded, I intend to attach a watch to a scope property and apply colors to the map based on that pr ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

Animation that responds to scrolling movements

Is there a way to animate text based on scrolling? <p class="class">TEXT</p> transform:translateX(-500px);opacity:0; transform:translateX(0px);opacity:1; ...

Deleting multiple data records in PHP/SQL by using a Select Option

Currently, I have developed a system that allows for the deletion of multiple data using a select option. However, I am facing some issues with this functionality. When only one data is selected and the delete button is pressed, it successfully deletes the ...

Is there a way to ensure that the function within the 'for loop' is executed prior to sending the response in NodeJS?

Utilizing bluebird for this task, my main goal is to ensure that the function `get_like_status(email, results[i].id)` located at the end of the for loop runs before sending out the headers. Currently, I am encountering an issue where the array list retur ...