Check fields in JavaScript: typical patterns

Sometimes we need to check if a field has a certain pattern (e.g. alphanumeric or valid email). We can do it using the test() method to test it against a regular expression.

Let's check some typical patterns:

javascript
// Defining a random string
let string = 'Defining a random string';

// Test if a string has only numbers
(/^[0-9]+$/).test(string); // false

// Test if a string is alphanumeric
(/^[0-9A-Za-z]+$/).test(string); // false

// Test if a string is alphanumeric with accents
(/^[0-9A-Za-zÀ-ÿ]+$/).test(string); // false

// Test if a string is alphanumeric with accents, spaces, underscores or dashes 
(/^[-_ A-Za-zÀ-ÿ]+$/).test(string); // true

// Test if a string has a mail pattern
(/\S+@\S+\.\S+/).test(string); // false

// ~~~~~
// Hints
// ~~~~~
// ^  → Start of string
// $  → End of string
// +  → Matches all the chars (not only the first one)
// \S → Matches any char that is not a whitespace (spaces, tabs, line breaks)

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.