1.Date Validation:
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
function isDateValid(date) {
return datePattern.test(date);
}
// Example usage:
const validDate = "2023-11-07";
const invalidDate = "11/07/2023";
console.log(isDateValid(validDate)); // true
console.log(isDateValid(invalidDate)); // false
2.Time Validation
const timePattern = /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
function isTimeValid(time) {
return timePattern.test(time);
}
// Example usage:
const validTime = "15:30";
const invalidTime = "25:00";
console.log(isTimeValid(validTime)); // true
console.log(isTimeValid(invalidTime)); // false
3.Email Validation:
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
function isEmailValid(email) {
return emailPattern.test(email);
}
// Example usage:
const validEmail = "example@example.com";
const invalidEmail = "invalid-email";
console.log(isEmailValid(validEmail)); // true
console.log(isEmailValid(invalidEmail)); // false
4.User name validation:
const usernamePattern = /^[a-zA-Z0-9_-]+$/;
function isUsernameValid(username) {
return usernamePattern.test(username);
}
// Example usage:
const validUsername = "john_doe-123";
const invalidUsername = "user@name";
console.log(isUsernameValid(validUsername)); // true
console.log(isUsernameValid(invalidUsername)); // false
Top comments (0)