Utilizing custom validity for asynchronous validation of forms

I am implementing a feature where users can only submit the form if the user does not already exist. To achieve this, I have created a custom rest API to check if the entered user already exists either on input blur or form submission. This approach has been successful so far.

The most challenging aspect is setting the custom validity for error handling. My goal is to leverage native form validation and error handling functionalities as much as possible. Therefore, I dynamically set and unset the pattern attribute accordingly.

Issue 1: When submitting the form by pressing enter, the message for invalid input is not displayed. (Is there a way to manually trigger the form to display the validity message?)

Issue 2: Upon entering an invalid name, submitting, then correcting it to a valid name and submitting again, the validation error message briefly appears and then disappears. (Considering that preventDefault must be called synchronously, should I re-submit the form when the input is valid and remove the event listener for submit to allow the form to be submitted?)

I have prepared a codepen to demonstrate the scenario: https://codepen.io/MartinMuzatko/pen/BdWmBg?editors=1010

The following code addresses my concerns:

usernameInput.addEventListener('blur', async (e)=>{
    let isValid = await isUserValid(e.target)
    console.log(isValid)
})

form.addEventListener('submit', async (e)=>{
    e.preventDefault()
    let isValid = await isUserValid(usernameInput)
    console.log(isValid)
})

Your assistance is greatly appreciated!

Sincerely, Martin

Answer №1

To activate the validation process, simply employ javascript's checkValidity() method.

form.addEventListener('submit', async (e)=>{
    e.preventDefault()
    e.target.checkValidity(); //ensure validity
    let isValid = await checkUserValidity(usernameInput)
    console.log(isValid)
})

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

Sort the table entries and update the identifier

Within my table, there is an [object HTMLInputElement] and I am trying to change the id of this element. However, the usual method I am using doesn't seem to be working: `function BindFunctions() { $('table[id*="tbl_main"]').tables ...

Enhance your online shopping experience with a personalized touch by incorporating an Ajax add to cart button on

Currently, I am working on customizing the add to cart button on a single product page. After implementing an ajax call solution from LoicTheAztec's post here, I have successfully added the feature. The code works perfectly fine, but now I am faced w ...

Instructions for integrating AJAX into a PHP script

I am looking to incorporate AJAX into my PHP file so that when I delete an item from a list, the data automatically reloads and the list is updated with the new information. I have created a list of all my data along with a delete button. Below is the PH ...

What is the best way to effectively showcase data retrieved from an API in a React application?

I am attempting to showcase an array of users retrieved from the JSONPlaceholder API: function App() { const [ data, setData ] = React.useState([]); React.useEffect( () => { axios .get('https://jsonplaceh ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

Display the message "Please complete this selection" for the Radio Field in the HTML form

I am facing an issue with error message display in my form. The text input field shows a nice message saying "Fill out this field", but the Radio and Dropdown fields do not show any error messages when left empty. How can I ensure that error messages are ...

Display array information within a table using ajax

Currently working with the Zend Framework to develop a website. I have an array called $shadow which contains IDs of individuals. The query for $shadow runs smoothly in the Model and gets called in the Controller without any issues. However, now I need t ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

Tips for adding a child div to encase the inner content

Can someone help me figure out how to use pure JS (not jquery) to add a <del> inside the <div> that contains the text 'abc'? For practice purposes, I am not allowed to use innerHTML method, inline CSS, or jquery. Just plain JS. <h ...

Managing click events in Javascript with Selenium Webdriver

Currently utilizing Selenium Webdriver for my testing. The test-case involves: Logging in to the site. Clicking on the Notifications link. I am experiencing an issue when attempting to click on the notification link. Here is a snippet of the HTML code c ...

Troubleshooting problem with specifying conditions in DoCmd.OpenReport

Struggling to generate an invoice report due to issues with the Cmd.OpenReport Function. The query for the invoice includes a parameter. SELECT EMPLEADOS.CODIGO, EMPLEADOS.NOMBRE, PAGOS.Fecha, PAGOS.Descripcion, CONCEPTOS.Descripcion, DETALLE_PAGO ...

The generation of "id" tags is incorrect when using Angular's *ngFor directive in conjunction with the `mat-button-toggle`

I am attempting to create a list of buttons from an array: <div class="card-container"> <mat-button-toggle *ngFor="let button of buttonsFromApi" id={{button.id}} class="problemButton" [disabled]="sso.invalid" >{{button.displayName}}</ma ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

The date format is malfunctioning -> Error: The date provided is not valid

My goal is to convert the date format from 2022-01-17T21:36:04.000Z to January 18th using the npm package, dateFormat. I found success with the following code snippet: const date = dateFormat("2022-01-17T21:36:04.000Z", "mmmm dS"); However, when trying t ...

Is there a way to extract osclass theme HTML from a plugin using JavaScript?

I've created a variable named btn which I'm assigning to a document.querySelector() function. The query selection seems correct as it successfully grabs the desired element when tested in the browser console. However, the assignment returns null. ...

Struggling to eliminate quotation marks from the JSON string

I'm struggling to remove the double quotes from my json string. Below is the code I am using: var values = {}; $.each($('#regForm :input'), function(i, field) { if (field.name == "submit") { dele ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

Verify whether an AJAX request or HTTP connection is currently in progress

One of the functionalities on my website involves a long polling jQuery AJAX function. This particular AJAX call has a time-out of 50 seconds and then runs again, continuously checking for any changes on the server. However, there are instances when the l ...

Retrieve JSON data and use a button to sort and display markers on a Google Map

Is it possible to modify my function in order to use different PHP files with separate buttons without duplicating the code? Currently, I have a function that displays markers on an external HTML page when a button is clicked. The data is retrieved from fi ...