Is it possible to develop a function that can verify various input values and modify their appearance as needed?

I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left empty, I'd like to change the style of that input box to display a red color. I have successfully implemented this for text inputs, but I'm wondering if there's a more efficient way to loop over all inputs and apply this functionality. Additionally, I'm open to suggestions on how to handle spans within the form elements, so any insight or examples would be greatly appreciated.

but.addEventListener("click", () => {
    if (firstname.value == "" || lastname.value == "") {
        
        firstname.style.backgroundColor = "rgba(200,0,0,.4)";
        lastname.style.backgroundColor = "rgba(200,0,0,.4)";
        span.style.display = "block";
        span.innerHTML = "Please enter a valid Name";
    }
    if (age.value == ""){
        span.style.display = "block";
        age.style.backgroundColor = "rgba(200,0,0,.4)";
        span.innerHTML = "Please enter your age";
    }  if (isNaN(age.value) == true ){
        span.style.display = "block";
        age.style.backgroundColor = "rgba(200,0,0,.4)";
        span.innerHTML = "Please enter a valid Age";
    }  if (job.value == "") {
        span.style.display = "block";
        job.style.backgroundColor = "rgba(200,0,0,.4)";
        span.innerHTML = "Please enter a role";
    }  if (email.value == "") {
        span.style.display = "block";
        email.style.backgroundColor = "rgba(200,0,0,.4)";
        span.innerHTML = "Please enter an email";
    }  if (phone.value == "") {
        span.style.display = "block";
        phone.style.backgroundColor = "rgba(200,0,0,.4)";
        span.innerHTML = "Please enter phone number";
    }
    
})

Answer №1

If you're looking to validate elements using a loop, this code snippet should do the trick for you.

The function `validateInputs` accepts an array of elements (`inputCollection`) to be validated and an error span as a placeholder. It checks if the input value matches the default value specified in the `data-default` attribute, and if not, appends the error message from the `data-errormessage` attribute to the error span.

function validateInputs(inputCollection, errorspan){
    for(let i = 0; i < inputCollection.Length; i++){
        let defaultValue = inputCollection[i].getAttribute('data-default');
        let errorMessage = inputCollection[i].getAttribute('data-errormessage');
        if(inputCollection[i].value === defaultValue || (!isNaN(defaultValue) && isNaN(inputCollection[i].value))){
            errorspan.innerHTML += `${errorMessage}`; 
        }          
    }
}

This implementation avoids adding styles via JavaScript and suggests using CSS instead for styling purposes.


Update 1

In response to your queries:

- The `data-default` attribute represents the default values (e.g., empty string for name, number for age).

- The `data-errormessage` attribute stores detailed error messages corresponding to each input element.

To clarify the functionality, see the following snippet:

document.getElementsByTagName('button')[0].addEventListener('click', function(){
    var col = document.querySelectorAll('input[data-default]');

    for(let i = 0; i < col.length; i++){
        let defaultValue = col[i].getAttribute('data-default');
        if(col[i].value === defaultValue || (!isNaN(defaultValue) && isNaN(col[i].value))){
            col[i].classList.add('hasError');
        }else if(col[i].classList.contains('hasError')){
            col[i].classList.remove('hasError');
        }          
    }
});
.errormessage{
   display: none;
}
.hasError{
   background:#f00;
}

.hasError + span.errormessage{
   display:block;
}
<form>
    <div>
        <input type='text' data-default="0" name='age' />
        <span class='errormessage' >some error message for the age</span>
    </div>
    <div>
       <input type='text' data-default="" name='name' />
       <span class='errormessage' >some error message for the name</span>
    </div>
</form>
<button>validate</button>

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

An issue occurred while attempting to utilize fs.readFileSync

Attempting to change an uploaded image to base 64 format var file = e.target.files[0]; var imageFile = fs.readFileSync(file); var encoded = new Buffer(imageFile).toString('base64'); An error is encountered: TypeError: __W ...

How to remove outer quotes from JSON data in Reactjs after using JSON.stringify

When using JSON.stringify on a Json data, I noticed that the resulting string includes double quotes at the beginning and end. For example: x = {fieldId: 536, value: {value: 341, display_value: "ABCD"}} After using JSON.stringify, the result looks like t ...

Error message: Unexpected token "(" in the asynchronous aspect of Meteor

Currently running meteor version 1.5.1, I am facing a bug while attempting to import an npm module (kraken-api) on the server side: import KrakenClient from 'kraken-api'; > W20170726-22:02:48.177(2)? (STDERR) packages/modules.js:677 ...

Ensuring the node array is easily accessible within the view

I am currently working on building a simple messaging system using express/nodejs. Although I have successfully implemented the feature to send messages to all users, I now want to enable users to have private 1-to-1 conversations. My aim is straightforwa ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...

Route creation unsuccessful while attempting to both download a file and send a response message, resulting in the error "Headers cannot be set after they have been sent to the client."

I'm currently working on setting up a route that will allow users to download a file and receive a response message in the HTML. I attempted to use the download function from express JS, but encountered some issues. Here is the code I am using: route ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

What is the best way to ensure that the Next.js app listener is attached before the 'load' event of the window is triggered?

Recently, I started working with next.js, incorporating TypeScript in version 13.5.5. One crucial requirement for the application is that it must be placed within an iframe and communicate with the parent/host through the window.postMessage event. To achie ...

Leveraging Vue js components while utilizing it from a content delivery network (CDN

I'm attempting to utilize the ButtonCounter component as a demonstration (source: https://vuejs.org/guide/essentials/component-basics.html#defining-a-component), but I am facing difficulties in getting it to function properly. I am utilizing Vue.js 3 ...

Utilize the Twitter Bootstrap modal feature to play autoplaying Youtube videos that automatically pause when

Similar Question: How do I halt a video using Javascript on Youtube? I am curious about how I can utilize the modal feature in Twitter Bootstrap to automatically play a Youtube video, and when a user clicks the "close" button, it will cease the video ...

Next.js server component allows for the modification of search parameters without causing a re-fetch of the data

I have a situation where I need to store form values in the URL to prevent data loss when the page is accidentally refreshed. Here's how I am currently handling it: // Form.tsx "use client" export default function Form(){ const pathname ...

How come my useEffect still contains outdated data?

I have encountered an issue with my useEffect in a React component. Despite having all the necessary dependencies, the state does not update after the useEffect completes. It always displays the previous render. Below is the code snippet of the hook: exp ...

Using the setTimeout function is essential for successfully extracting values in a Jquery each loop. Without

I created a loop to adjust the padding on an image tag placed atop another image. Strangely, it was only capturing the first one or two values until I added a setTimeout function, which seemed to fix the issue. Below is the jQuery code: $(document).ready ...

Learn the trick to make this floating icon descend gracefully and stick around!

I'm trying to create a scrolling effect for icons on my website where they stay fixed after scrolling down a certain number of pixels. I've managed to make the header fixed after scrolling, but I'm unsure how to achieve this specific effect. ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Mongoose Exception: Question does not have a constructor

After coming across numerous questions on stack overflow related to this error without finding a solution that works for me, I've decided to ask my own question. (probably due to my limited understanding of javascript/node/mongoose) The modules I am ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

An effective way to connect the ng-model of a <select> element with ng-options within an ng-repeat loop

My task list consists of: [{ Title: "Title1", Position: "9" },{ Title: "Title2", Position: "1" },{ Title: "Title3", Position: "5" },{ Title: "Title4", Position: "7" }] I am attempting to generate a series of <select> ...