Tips for implementing validations on a table that changes dynamically

I encountered an issue in my code while working on a dynamic form for age with unobtrusive client-side validation. The problem is that the validation is row-wise, but it behaves incorrectly by removing other rows' validations when I change one.

Below is the snippet of my code:

function dob_police(){
    var age = document.getElementById('p_age').value;

    if(age < 20){
          document.getElementById('wrong_dob_alert').style.color = 'red';
          document.getElementById('wrong_dob_alert').innerHTML = 'Age must be 20 above';
          }
          else{
          document.getElementById('wrong_dob_alert').style.color = 'green';
          document.getElementById('wrong_dob_alert').innerHTML = '✓';
          }
}
<div class="form-group">
            <label>Age</label>
            <input type="number" class="form-control form-control-sm" id="p_age" name="age" required onkeyup="dob_police()" value="<?php echo $row['age']; ?>">
            <small id="wrong_dob_alert"></small>
        </div>

Answer №1

To enhance the validation process, you can pass the reference of the current object using this to the specific DOM element with the attribute

onkeyup="dob_police(this)"
. By doing so, you can access its value and the adjacent element that displays the validation styling. It is also possible to eliminate the ID since it does not need to be unique.

function dob_police(tempThis){
    var age = tempThis.value;

    if(age < 20){
        tempThis.nextElementSibling.style.color = 'red';
        tempThis.nextElementSibling.innerHTML = 'Age must be 20 above';
     }
     else{
        tempThis.nextElementSibling.style.color = 'green';
        tempThis.nextElementSibling.innerHTML = '✓';
     }
}

Answer №2

This could seem like it's going a bit overboard, but here's an example of how you can enhance the customization options using HTML with a JSON data attribute.

var ageValidator = function(item, notificationElement, validationRules, event) {
    notificationElement.classList.remove('error', 'valid');
    if(parseInt(validationRules.values.min, 10) < event.target.value) {
        notificationElement.classList.add('valid');
        notificationElement.innerHTML = validationRules.validMessage;
    } else {
        notificationElement.classList.add('error');
        notificationElement.innerHTML = validationRules.errorMessage;
    }
};

[...document.querySelectorAll('.form-group')].forEach( item => {
    
    let inputElement = item.querySelector('[data-validator]');
    let validationRules = JSON.parse(inputElement.dataset.validator);
    let notificationElement = item.querySelector('.notification');
    
    validationRules.events.forEach( validationEvent => {
        inputElement.addEventListener(
            validationEvent,
            (event) => {
                window[validationRules.function](
                    inputElement,
                    notificationElement,
                    validationRules,
                    event
                )
            }
        );  
    })
      
});
.error {
    color: red;
}

.valid {
    color: green;
}
<div class="form-group">
  <label>Age</label>
  <input type="number" class="form-control form-control-sm" name="age" required value=""
   data-validator='{"function":"ageValidator", "values":{"min": "20"}, "errorMessage":"Age must be 20 above", "validMessage":"✓", "events": ["keyup", "mouseleave"]}'>
  <small class="notification"></small>
</div>

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

Tips on extracting the image URL from a canvas element using Selenium in Java and leveraging JavascriptExecutor

My main objective is to extract the image URL from a canvas container. Here is what I have attempted: JavascriptExecutor jse = (JavascriptExecutor) driver; Object imageURL = jse.executeScript("arguments[0].toDataURL('image/png');", canvas); Un ...

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...

Choose your location with React: Country -> Province/State -> City?

It seems to be a common need for people to have a feature where selecting a country would then filter down the provinces or states available for that country, and then from there, narrow down to city selections. I've been searching NPM for a solution, ...

Passing User Authentication State from Express/Passport to a React Client: A Step-by-Step Guide

I want to pass a basic boolean value const isLoggedIn = true; (provided by Passport) from my Express backend to my React frontend. I'm looking for an alternative to embedding it in the HTML through a templating engine. This seems like a common req ...

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

JQuery selector is successfully working while vanilla JavaScript is not functioning as expected

This problem is unique because I am experiencing issues with querySelector and querySelectorAll in my JavaScript code. While JQuery works fine, vanilla JS does not work as expected. I would appreciate any insights on why this might be happening. Thank you ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Overwriting the responseText from a previous XMLHttpRequest in JavaScript

I am working on updating two different JavaScript charts displayed on a PHP page by making sequential XMLHttpRequests using JavaScript. The goal is to update the data on these charts simultaneously. <!DOCTYPE HTML> <html> <head> <scri ...

Looping through elements using JQuery in groups of 2

Let's say I have the following array: Mike Blue Jakob Red Luis Orange and I'm using this JQuery code to loop through it: $.each( arr, function( index, value ){ $( ".div" ).append( "" + value + "" ); } }); Now, I want to modify the ...

Retrieve only the most recent input value

Currently, I am working with a text input to capture user input. As of now, here is my code snippet: $(myinput).on('input', function() { $(somediv).append($(this).val()); }); While I want to continue using the append function, I am facing an i ...

HAproxy: unique error handling for OPTIONS and POST requests with 503 errorfile

Our Web application utilizes ajax calls to a backend that operates on a different domain, requiring CORS. The backend setup includes an HAproxy 1.4.22 along with multiple Wildflys running on the OpenShift PaaS. During times when a Wildfly instance is unava ...

Sending an array as a query string

I am trying to send an array to my server using jsonp. Here is an example of the JSON I want to pass: ["something","another_thing",4,{"iam" : "anobject"}] However, I am unsure about how to actually pass an array. I thought it might work like this: some ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

What are the best practices for dynamically handling variables in JavaScript?

I am looking to dynamically work with variables and store their references in a collection. My first question is: How can I save a variable reference (not its value) in a collection? For example: var apple = "A delicious fruit"; var banana = "A yellow f ...

Utilize JavaScript to parse and retrieve specific data from an SVG file in XML format

I am attempting to retrieve an svg file using jquery or javascript. Here is an example of the svg code: <svg width="111" height="123" xmlns="http://www.w3.org/2000/svg"> <g> <title>Layer 1</title> <rect fill="#ffffff" strok ...

Troubleshooting problems with Window.postMessage()

When attempting to fetch data from different domains, I am facing an issue. However, if I run the code on the same server, everything works perfectly fine and I am able to retrieve the message. index.html: <head> <title>Test 1</title&g ...