Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be.

Here is the JavaScript code:

input.parentNode.querySelector(':valid')

And here is the HTML input that is being validated:

<input type="tel" id="fos_user_registration_form_mobileNumber" name="fos_user_registration_form[mobileNumber]" required="required" pattern="^0[0|1|2|3|4|5|6|7|9]\d{8}$" maxlength="10">

But is there a better way to achieve this validation?

Answer №1

If you're searching for the validity property, then look no further:

The getter for the validity attribute will retrieve a ValidityState object that indicates the various validity states of the element. This object is dynamic and constantly updating.

One key state within this object is the boolean valid flag:

If (input.validity.valid) {
    // Element is valid
} else {
    // Element is not valid
}

You can also use matches:

If (input.matches(":valid")) {
    // Element is valid
} else {
    // Element is not valid
}

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

Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered. Should I create a mock object f ...

Utilizing JQuery to make Google listings easily findable

Implementing Google Places for a location text box has been successful. However, I am now looking to create a class-based implementation so that I can use it with multiple places effortlessly. Is it possible to achieve this using JQuery? <script type ...

Hiding a parent DIV in JS based on specific content: Here's how

I need help figuring out how to hide multiple parent DIVs based on the content of a specific child DIV. Here's an example: <div class="report-per-day"> <div class="report-day">26 May 2022</div> <div class=" ...

My AJAX request seems to be redirecting to my PHP file instead of simply returning the response text. What could be causing this issue?

I am currently working on a project for my Web Engineering course and I am incorporating jQuery to execute an AJAX request to my PHP file using the POST method. The task specifies that "each time the [submit] button is pressed, the form data should be disp ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

Tips for sending information from PHP to an AJAX function

Hello, I am in the process of learning PHP and I am attempting to retrieve data from a PHP file using the script below. However, I am not receiving any response: $.ajax({ type: 'POST', url: "mark_mod.php", ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

Guide to utilizing an if statement to return a string as the title in a Tooltip pro

When attempting to dynamically set the title of a tooltip based on a function and using an if statement, I encountered an error. const getStatusMessage = (answer: AnswerStatus) => { if (answer == AnswerStatus.ANSWER_SUBMITTED || answer == AnswerStatus ...

Tips for Sending <Div> Data to a Servlet

I attempted to pass the content of an entire div in a form action URL using JavaScript. However, when I try to retrieve this request parameter as a String on the servlet side, it is returning [object Object]. Below is my code for the form and JavaScript: ...

Utilizing AngularJS to create a vertical calendar

Looking to create a vertical navigation displaying the date and day for the current week using angularjs. When clicking on the navigation div, I want an alert with the selected date to appear. I attempted this in Plunker using various templates, but was u ...

Mocha avoids running the test

Hi everyone, I am a beginner in Node.js and JavaScript and I'm having trouble understanding why Mocha is skipping over my test. I know that I may not be using the request and supertest libraries correctly, but I really want to figure out why, when it ...

Add into clickhouse JSONEachRow with nested data structure

Here is the table structure I am working with: SET flatten_nested = 0; CREATE TABLE test.hm ( customDimensions Array(Nested(index Nullable(Int64), value Nullable(String))) ) engine = Memory; I have been attempting to insert data into this table us ...

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

[filepond] in order to enroll using the serverId value received from the server

Using 'filepond' within a Vue application is causing an issue. In the "process" function, the ID value obtained after transferring the file to the server (response.id) needs to be registered as 'serverId' of the file. Upon checking the ...

What are the steps for incorporating React into an existing website?

Currently, I have a website built with Express and I am looking to incorporate React into specific pages. What is the most effective method to integrate it while utilizing all the resources available through create-react-app? I understand that I can manua ...

A guide to accessing array elements (JSON) in Angular

Having a variable named $scope.informationData, the data appears like this when outputted by console.log: {"completed":100,"pending":50,"defects":20,"overdue":10} However, when trying to display just the "overdue" value in my HTML using the following cod ...

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...