Blur-triggered form validation

Within my webpage, I'm facing an issue with 5 input fields that need to be validated on blur. Instead of relying on alert boxes, I aim to display either an error or success message through DOM scripting. Despite trying various codes, nothing seems to be working as intended. To begin with, I have a simple code snippet to test if it runs at all. This snippet is meant to trigger an alert box, but it's failing to do so. Ideally, I'd like to avoid using innerHTML and keep all functions contained within the javascript itself. Here's a snippet of my HTML:

<div id=fNID>
                <label for="firstNameID">First Name: </label>
                <input id="firstNameID" type="text" name="firstNameA" value="" />
                <span> </span>
            </div>

            <div id=lNID>
                <label for="lastNameID">Last Name: </label>
                <input id="lastNameID" type="text" name="lastNameA" value="" />
                <span> </span>
            </div>

And here's a snippet of my JavaScript:


    firstNameID = document.surveyForm.getElementById("firstNameID");
    document.surveyForm.getElementById(fN).addEventListener("blur", validateName);
    function validateName() {
        var nameRegEx = /[a-zA-Z]+/;
        var firstNameID = document.getElementById("firstNameID");

        if (fN.matches(nameRegEx)) {
            alert("Success!")
        } else {
            alert("error")
        }
    }


    window.addEventListener("load", setupForm, false);
}

Answer №1

One interesting approach to input validation is demonstrated in Bootstrap. They utilize div elements following the input field to display either a valid or invalid message, depending on the input entered:

<div class="form-group">
    <label for="uname">Username:</label>
    <input class="form-control" id="uname">
    <div class="valid-feedback">Valid.</div>
    <div class="invalid-feedback">Please fill out this field.</div>
</div>

Bootstrap's CSS classes make use of the pseudo-classes :valid and :invalid to style the display accordingly.

By employing the setCustomValidity() method in JavaScript, you can specifically assign these pseudo-classes to the input element.

input.setCustomValidity("input is invalid")

this will set the :invalid pseudo-class to the input.

input.setCustomValidity("")

will assign the :valid pseudo-class.

Here is a practical demonstration:

const input = document.getElementById('uname');

function makeValid() {
  input.setCustomValidity('');
}

function makeInvalid() {
  input.setCustomValidity('a problem');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<h3 class="m-2">Bootstrap input with validation</h3>
<form class="was-validated mx-2">
  <div class="form-group">
    <label for="uname">Username (required):</label>
    <input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname">
    <div class="valid-feedback">Valid.</div>
    <div class="invalid-feedback">This field is invalid.</div>
  </div>
</form>
<div class="m-2">
  <p>Use setCustomValidity() to change input state:</p>
  <button onclick="makeValid();">:valid</button>
  <button onclick="makeInvalid();">:invalid</button>
</div>

It's important to note that many browsers offer built-in support for showing validation messages on inputs. Here's a simple example that does not rely on any Bootstrap functionality:

const input = document.getElementById('uname');

function makeValid() {
  input.setCustomValidity('');
}

function makeInvalid() {
  input.setCustomValidity('this is invalid');
}
body {
  background-color: #aaa;
}

.m-2 {
  margin: .5rem;
}

.mt-5 {
  margin-top: 1rem;
}
<body>
  <h3 class="m-2">Generic input with validation</h3>
  <form class="mt-5">
    <label for="uname">Username:</label>
    <input type="text" id="uname" placeholder="Enter username" name="uname">
    <p>Use setCustomValidity() to change input state:</p>

    <button onclick="makeInvalid();">input:invalid</button>
  </form>
  <div class="m-2">
    <button onclick="makeValid();">input:valid</button>
  </div>
</body>

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

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Error: Null value detected while trying to access the property 'appendChild'

Can anyone help me with this error? Uncaught TypeError: Cannot read property 'appendChild' of null myRequest.onreadystatechange @ script.js:20 Here's the code snippet where I'm facing the issue // index.html <html> <he ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Highly complex regular expressions in nth-check causing inefficiencies during npm installation of react-router-dom

Feeling new and inexperienced with how to react, I attempted to execute the command "npm i react-router-dom" but it ended up stopping the download process and displaying several errors. In my search for a solution, I stumbled upon this reference to some ...

Learning how to toggle default snippet keywords on and off based on specific scenarios within the Angular Ace Editor

Within the Ace editor, I have incorporated custom snippets alongside the default ones. However, there are certain scenarios where I would like to exclusively display the custom snippets and hide the default ones. Is there a way to disable or conceal the ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Performing a AJAX POST call to the latest Google Analytics V4 API

Recently, the Google Analytics v4 API was updated and now requires POST requests instead of GET requests. Unfortunately, there are not many examples available yet... I managed to obtain the accessToken, but when I attempt the following POST request, I alw ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

Issue: Error occurs when using _.sample on an array containing nested arrays

I am working with an array of arrays that looks like this: [[0,0], [0,1], [0,2], [0,3]...] My goal is to randomly select N elements from the array using Underscore's _.sample method: exampleArr = [[0,0], [0,1], [0,2], [0,3]...] _.sample(exampleArr, ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

How can I retrieve information from a topic using kafka-node?

Having trouble reading data from a Kafka server? You may encounter an error message stating that the topic does not exist. Here are some questions to guide you: 1- How can I ensure that my Kafka connection is established? 2- What is the process for retri ...

Sending information back to the server without causing a postback, all while remaining unseen

I have a straightforward JavaScript function on my ASP.NET page that writes data to a hidden field. However, in order to retrieve this data the form needs to be submitted back to the server. The issue is that submitting the form causes the page to reload ...

Monitoring changes in an array of objects using AngularJS's $watch function

Exploring the world of AngularJS, I'm on a quest to solve a challenging issue efficiently. Imagine having an array of objects like this: var list = [ {listprice: 100, salesprice:100, discount:0}, {listprice: 200, salesprice:200, discount:0}, {listpr ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...

What is the process for obtaining a JSON result after completing an upload?

I recently started working with the razor view engine and I have encountered a situation where I need to upload an image using the Change event of an image browser. The jQuery function for this task is as follows: $("#billUpload").change(function (){ ...

Javascript Google Maps API is not working properly when trying to load the Gmap via a Json

Trying to display a map using Gmaps and Jquery Ajax through JSON, but encountering difficulty in getting the map to appear on the page. The correct coordinates are being retrieved as confirmed by testing in the console. Puzzled by why it's not showin ...

Sharing asynchronous data between AngularJS controllers

Among the multitude of discussions on sharing data between controllers, I have yet to come across a satisfactory solution for my particular scenario. In my setup, one controller fetches data asynchronously using promises. This controller then creates a co ...

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...