Overview
The most efficient way to determine if a user’s input matches a specific format—such as phone numbers, zip codes, or email addresses—is to use the test() method of the regular expression object.
This article explains how to implement real-time input validation, ranging from simple string searches to complex format verification.
Specifications (Input/Output)
- Input: Text entered into a phone number field (allowing hyphens).
- Output: An error message displayed if the format is incorrect.
- Operation:
- Remove hyphens (-) from the entered string.
- Determine if the formatted string is a “10 or 11-digit number starting with 0.”
- Display a warning message if conditions are not met.
Basic Usage
Execute the test() method on a regular expression literal (/pattern/). It returns true if there is a match and false if there is not.
| Method | Meaning | Return Value |
regex.test(string) | Checks if the string matches the pattern | true / false |
// Check if 'J' is included
console.log(/J/.test('JavaScript')); // true
// Check if it starts with 'iP' (^ means start)
console.log(/^iP/.test('iPhone')); // true
// Check if it contains a digit (\d means digit)
console.log(/\d/.test('suzuki')); // false
// Check if 'Java' is followed by anything (.* means any characters)
console.log(/Java.*/.test('JavaScript')); // true
Full Code (HTML / JavaScript)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Regex Validation Example</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="tel"] {
padding: 10px;
width: 100%;
max-width: 300px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
/* Style for errors */
.input-error { border-color: #d32f2f; background-color: #ffebee; }
.error-message {
color: #d32f2f;
font-size: 0.9em;
margin-top: 5px;
display: none; /* Hidden by default */
font-weight: bold;
}
.error-message.visible { display: block; }
</style>
</head>
<body>
<div class="form-group">
<label for="telInput">Phone Number (with or without hyphens)</label>
<input type="tel" id="telInput" placeholder="Example: 090-1234-5678">
<div id="errorMsg" class="error-message">
* Please enter a 10 or 11-digit number starting with 0.
</div>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
/**
* Get references to HTML elements
*/
const telInput = document.querySelector('#telInput');
const errorMsg = document.querySelector('#errorMsg');
/**
* Function to validate the phone number format
*/
const validatePhoneNumber = () => {
// 1. Get the input value
const rawValue = telInput.value;
// If input is empty, clear errors and stop processing
if (rawValue === '') {
errorMsg.classList.remove('visible');
telInput.classList.remove('input-error');
return;
}
// 2. Remove hyphens to normalize (make it digits only)
const trimmedValue = rawValue.replace(/-/g, '');
// 3. Validation using regular expression
// ^ : Start of string
// 0 : First character is 0
// [0-9]{9,10} : 9 to 10 digits follow (Total 10-11 digits)
// $ : End of string
const pattern = /^0[0-9]{9,10}$/;
// Check if it matches using the test() method
const isValid = pattern.test(trimmedValue);
// 4. Update UI based on results
if (isValid) {
// Correct format
errorMsg.classList.remove('visible');
telInput.classList.remove('input-error');
} else {
// Incorrect format
errorMsg.classList.add('visible');
telInput.classList.add('input-error');
}
};
// Execute validation on every keyup event
telInput.addEventListener('keyup', validatePhoneNumber);
Customization Tips
- Changing Regex Patterns: Replace the regular expression to match your target.
- Zip Code (Example: 123-4567):
/^\d{3}-\d{4}$/ - Alphanumeric characters only:
/^[a-zA-Z0-9]+$/ - Katakana only:
/^[\u30A0-\u30FF]+$/
- Zip Code (Example: 123-4567):
- Error Display Timing: Currently set to
keyup(immediately after typing), but changing it toblur(when focus is lost) allows you to check only after the user has finished typing.
Important Notes
- Statefulness of the test() Method: If you add the
g(global) flag to a regular expression,test()remembers the position of the last match. For simple checks, do not use thegflag or ensure you create a new regex object each time. - Importance of Full Matching: If you forget to use
^(start) and$(end), a partial match (e.g., “abc09012345678xyz”) will returntrue. Always specify both ends when validating the format of the entire input. - Security: Client-side (JavaScript) validation is intended to improve user experience. You must always re-validate data on the server side when submitting.
Advanced Applications
Password Strength Check with Multiple Conditions
This example determines if a password contains both “letters” and “numbers.”
const password = "password123";
// Does it contain letters?
const hasLetter = /[a-zA-Z]/.test(password);
// Does it contain digits?
const hasDigit = /[0-9]/.test(password);
// Is it at least 8 characters long?
const hasLength = password.length >= 8;
if (hasLetter && hasDigit && hasLength) {
console.log("Strong password");
} else {
console.log("Please use at least 8 characters including letters and numbers");
}
Conclusion
regex.test() is a method that allows you to instantly determine if an input value matches a specific pattern by returning a boolean. It enables the implementation of complex rules—such as digit repetitions or start/end specifications—that cannot be handled by simple string methods like includes(). This technology is essential for improving the quality of user forms.
