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

The color input click event does not work properly when triggered within a context menu event

This may sound a bit complicated, but let me try to explain it clearly. I'm working on a web app where I want users to be able to change the background color of certain divs. I plan to use a color picker interface for this purpose and utilize the con ...

Even after being removed from the DOM using Ajax load, JQuery continues to execute

Currently, within my Laravel 5.2 single page application development, I am faced with the following issue. I have an add.blade.php file and an edit.blade.php file, both containing a script with the same class name and id. When I use .load to load add.blade ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

What could be causing the <img src= ' '/> tag to malfunction in Express?

While learning about HTML, I noticed that simply using img src="...." worked fine. However, when working with Express, the same code did not work! The documentation mentioned that I needed to place the images in a folder named public, require(&ap ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

Dynamic drop-down navigation with rearranging menu

I am attempting to design a drop-down navigation bar with 2 rows. Initially, only 1 row is visible. Upon clicking the visible row, both rows should appear. Subsequently, when one of the 2 rows is clicked, only that specific row should be displayed. Below a ...

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

Utilizing jQuery to Trigger a Click Event on an Element Without a Class

What is the best way to ensure that the "click" event will only be triggered by an href element unless it does not have the "disablelink" class? Avoid processing the following: <a class="iconGear download disablelink" href="#">Download</a> P ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Gulp is showing an error of "Module Not Found" despite the module being present in the project

I've come across an unexpected issue and I'm at a loss for solutions. As part of my exploration into JS unit testing, I am configuring gulp with Jasmine. However, when I run my gulp build, I encounter the following error: Error: Cannot find modu ...

Securing Email and Password Data in Cypress Tests

Greetings! I trust everyone is in good spirits. My dilemma lies in the fact that I am hesitant to include email and passwords in version control. I am considering using environment variables in my cypress tests and utilizing secrets for runtime value pro ...

Instructions for inserting <tr></tr> after every fourth iteration of <td></td> in the loop

I am trying to create a list of twenty people with each tr containing 4 people, and I want to break from the loop after every fourth number. Each td value should be incremented in order. This is the code snippet I have been working on: <?php for ($i ...

In certain situations, the JavaScript code runs either before or after the print dialog is displayed when using the window

I am facing an issue with the print function on my web page. I want to display a thank you message to the user after they have either printed or cancelled the print dialog. Below is a simplified version of the print function code: function printThenThank ...

What is the best way to transform this into an HTML readable code?

While browsing through a template, I came across this code and I'm unsure of how to get it functioning. I've tried removing the comments, but unfortunately it doesn't seem to be working as expected. li.dropdown.navbar-cart ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...