How to check the input value length with JavaScript?

Sometimes, we want to check the input value length with JavaScript.

In this article, we’ll look at how to check the input value length with JavaScript.

How to check the input value length with JavaScript?

To check the input value length with JavaScript, we can set the submit handler of the form to a function that checks the input’s length.

For instance, we write:

<form>
  <input name='title' />
  <input type='submit' />
</form>

to add a form with a text and submit input.

Then we write:

const form = document.querySelector('form');
const input = document.querySelector('input[name="title"]');
form.onsubmit = (e) => {
  e.preventDefault()
  console.log(input.value.length)
}

to select the form and the text input with document.querySelector.

Then we set the form.onsubmit property to a function that calls e.preventDefault to stop the server-side form submission behavior.

Then we check the length of the input value with input.value.length.

Conclusion

To check the input value length with JavaScript, we can set the submit handler of the form to a function that checks the input’s length.