TypeScript Form Validation
Learn how to validate form fields using TypeScript, check user input, display validation messages, validate email and password fields, and handle form submission.
1. What Is Form Validation?
Form validation checks whether the information entered by a user satisfies the application's rules before the data is processed.
For example, a registration form may require a student's name, a valid email address, and a password that satisfies certain rules. TypeScript helps us write type-checked validation logic.
User Input
The user enters details into the form.
Validation
The application checks the entered values.
Result
Show errors or continue with valid input.
2. Required Field Validation
Required-field validation checks that a user has entered a value.
The trim() method removes leading and trailing whitespace
before the value is checked.
HTML
<input id="studentName" type="text" />
<p id="nameError"></p>
<button id="validateButton" type="button">
Validate Name
</button>
TypeScript
const nameInput =
document.getElementById("studentName") as HTMLInputElement | null;
const nameError =
document.getElementById("nameError");
const validateButton =
document.getElementById("validateButton");
if (nameInput && nameError && validateButton) {
validateButton.addEventListener("click", () => {
const name = nameInput.value.trim();
if (name === "") {
nameError.textContent = "Name is required.";
} else {
nameError.textContent = "Name accepted.";
}
});
}
Validation Rules
Empty Name
Display the message: Name is required.
Valid Name
Display the message: Name accepted.
trim() method prevents a value containing only spaces
from being treated as a valid name.
3. Email Validation
Email validation checks whether an entered address matches the application's expected format. A simple regular expression can be used for a basic format check.
function isValidEmail(email: string): boolean {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
console.log(isValidEmail("student@example.com"));
console.log(isValidEmail("invalid-email"));
Expected Output
true
false
The expression checks for a basic email-like format. It does not establish that an email address exists or that the user owns it.
4. Password Validation
An application may require a minimum password length and a combination of uppercase letters, lowercase letters, numbers, and special characters. The exact policy should match the application's security requirements.
function validatePassword(password: string): string[] {
const errors: string[] = [];
if (password.length < 8) {
errors.push("Password must contain at least 8 characters.");
}
if (!/[A-Z]/.test(password)) {
errors.push("Add at least one uppercase letter.");
}
if (!/[a-z]/.test(password)) {
errors.push("Add at least one lowercase letter.");
}
if (!/[0-9]/.test(password)) {
errors.push("Add at least one number.");
}
if (!/[^A-Za-z0-9]/.test(password)) {
errors.push("Add at least one special character.");
}
return errors;
}
const errors = validatePassword("hello");
console.log(errors);
Expected Output
[
"Password must contain at least 8 characters.",
"Add at least one uppercase letter.",
"Add at least one number.",
"Add at least one special character."
]
5. Confirm Password Validation
Confirm-password validation checks whether the password entered in two fields matches.
function passwordsMatch(
password: string,
confirmPassword: string
): boolean {
return password === confirmPassword;
}
console.log(passwordsMatch("Hello@123", "Hello@123"));
console.log(passwordsMatch("Hello@123", "Hello@456"));
Expected Output
true
false
6. Validating a Form on Submission
Use the form's submit event to validate the fields before
the application processes the form. Call preventDefault()
when validation fails.
HTML
<form id="registrationForm">
<input id="fullName" type="text" placeholder="Full Name" />
<input id="email" type="email" placeholder="Email" />
<button type="submit">Register</button>
</form>
<p id="formMessage"></p>
TypeScript
const form =
document.getElementById("registrationForm") as HTMLFormElement | null;
const fullName =
document.getElementById("fullName") as HTMLInputElement | null;
const emailInput =
document.getElementById("email") as HTMLInputElement | null;
const formMessage =
document.getElementById("formMessage");
if (form && fullName && emailInput && formMessage) {
form.addEventListener("submit", (event: SubmitEvent) => {
event.preventDefault();
const name = fullName.value.trim();
const email = emailInput.value.trim();
if (name === "") {
formMessage.textContent = "Please enter your name.";
return;
}
if (!isValidEmail(email)) {
formMessage.textContent = "Please enter a valid email.";
return;
}
formMessage.textContent = "Form validation successful.";
});
}
Validation Flow
Submit Form
The user clicks Register.
Validate Fields
Check name and email format.
Display Result
Show an error or success message.
7. Complete Registration Form Validation
This example combines name, email, password, and confirm-password checks into a single reusable validation function.
TypeScript
interface RegistrationData {
name: string;
email: string;
password: string;
confirmPassword: string;
}
function validateRegistration(
data: RegistrationData
): string[] {
const errors: string[] = [];
if (data.name.trim() === "") {
errors.push("Name is required.");
}
if (!isValidEmail(data.email.trim())) {
errors.push("Enter a valid email address.");
}
if (data.password.length < 8) {
errors.push("Password must contain at least 8 characters.");
}
if (data.password !== data.confirmPassword) {
errors.push("Passwords do not match.");
}
return errors;
}
const registration: RegistrationData = {
name: "Rahul",
email: "rahul@example.com",
password: "Hello@123",
confirmPassword: "Hello@123"
};
const validationErrors = validateRegistration(registration);
if (validationErrors.length === 0) {
console.log("Registration data is valid.");
} else {
console.log(validationErrors);
}
Expected Output
Registration data is valid.
8. Types of Validation
| Validation Type | Purpose | Example |
|---|---|---|
| Required Field | Ensures an essential value is entered. | Name cannot be blank. |
| Format Validation | Checks whether input matches an expected format. | Email format check. |
| Length Validation | Ensures a value meets a length rule. | Password has a minimum length. |
| Match Validation | Checks two related values. | Password and confirm password match. |
| Business Validation | Applies an application's business rules. | Age must satisfy the application's policy. |
| Server Validation | Verifies data on the trusted server. | ASP.NET Core validates submitted data. |
9. Form Validation Best Practices
Clear Messages
Explain what is incorrect and how the user can fix it.
Use TypeScript Types
Define interfaces for structured form data and type function parameters.
Validate on the Server
Repeat important validation on the server because browser checks can be bypassed.
Avoid Sensitive Error Details
Do not expose passwords, private tokens, or internal server details in browser messages.
10. Common Mistakes
- Checking only whether an input exists, rather than validating its value.
-
Forgetting to call
preventDefault()when custom validation must stop normal form submission. - Treating client-side validation as sufficient security.
- Assuming a regular expression proves that an email address exists.
- Failing to compare the password and confirm-password fields.
- Showing errors without explaining how the user can correct them.
Summary
- Form validation checks data before an application processes it.
- Required-field validation prevents blank values.
- Email validation checks a basic address format.
- Password validation enforces the application's password rules.
- Confirm-password validation checks whether both password values match.
- Form submit events let you validate inputs before continuing.
- TypeScript interfaces can describe the structure of registration data.
- Server-side validation remains essential for application security.