Skip to Content

Validate User Input with Regex in JavaScript

In this tutorial, you'll learn how to validate user input with regular expressions in JavaScript using the test() method. We'll play around with some different rules, but you can find some of the more common regular expressions here.

The test() method

The test() method is a built-in JavaScript method of the RegExp object that allows you to validate user input or other strings using regular expressions.

The method returns a boolean value, either true or false, confirming whether the validation has passed or not.

Test String Length

Here's an example that tests the length of a string, and returns true if the test passed, or false if it failed:

var regex = /^[A-Za-z]{1,9}$/;
var name = "Orangeable";
var result = regex.test(name);

console.log(result);
// false

In this case, we're testing the length of the name Orangeable. Our regular expression defines that the length of the name should be between 1 and 9 characters for it to pass the test. Here, the length is 10, so the test fails. For it to pass, we could either change our name to fit these constraints or increase the max allowable characters to 10:

var regex = /^[A-Za-z]{1,10}$/;

Now, if you run a new test with the updated rules, the result will be true.

Testing for Valid Email Format

If your application accepts and stores email addresses for user accounts, for example, you could create a rule to validate user input like this:

var regex = /(([0-9a-zA-Z\.\-\_]+(\.[0-9a-zA-Z\.\-\_]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = "hello@orangeable.com";
var result = regex.test(email);

console.log(result);
// true

This method does not confirm whether the email address is an actual address that exists on the internet. It only tests the format provided by the user. Since the email address provided is in valid email format, it passes the test.

Conclusion

Now that you know how to validate user input with regular expressions in JavaScript, you can add them to your front-end form validation of your applications going forward!

Created: August 08, 2022