Solve - checkValidity is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Rahul Bhosale

Solve - checkValidity is not a function Error #

The "checkValidity is not a function" error occurs when we try to call the checkValidity method on a value that is not an input or select DOM element. To solve the error, make sure to only call the checkValidity method on input or select elements.

typeerror checkvalidity is not a function

If you're using jQuery, make sure you're calling the method on a select or input element and not a collection of elements.

index.js
const btn = document.getElementById('send'); btn.addEventListener('click', function validate() { const collection = $('#fav_number'); console.log(collection); // ๐Ÿ‘‰๏ธ [input#fav_number] // โœ… Works console.log(collection[0].checkValidity()); // โœ… Also works console.log(collection.get(0).checkValidity()); });

We had to access the element at index 0 from the collection, so we can call the checkValidity method on an input element. Had we tried to call the method on the collection, we would get an error.

Here is a complete example how the error occurs in JavaScript.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input id="fav_number" class="fav_number" type="number" min="0" max="100" required /> <button id="send">Submit</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code:

index.js
const btn = document.getElementById('send'); btn.addEventListener('click', function validate() { const input = document.getElementsByClassName('fav_number'); console.log(input); // ๐Ÿ‘‰๏ธ [input#fav_number] // โ›”๏ธ TypeError: checkValidity is not a function console.log(input.checkValidity()); });

We called the checkValidity method on a collection of DOM elements and not on the input element and got the error back.

To solve the error, we have to call the method directly on the input element.

index.js
const btn = document.getElementById('send'); btn.addEventListener('click', function validate() { const collection = document.getElementsByClassName('fav_number'); console.log(collection); // ๐Ÿ‘‰๏ธ [input#fav_number] // โœ… Works console.log(collection[0].checkValidity()); });

If the error persists, console.log the value you're calling the checkValidity method on and make sure it's an input or select element.

Double check that you're not misspelling checkValidity as it is case sensitive.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee