Validation Functions - Done
Function
validateEmail(value)
Description
Validates that the provided string is properly formatted as an email address.
Prerequisites
Before using the validateEmail function, ensure that the validator library is installed in your project. You can install it using npm:
npm install validatorParameters
Parameter | Type | Description |
|---|---|---|
value | string | The email address to validate. |
Return Value
Property | Type | Description |
|---|---|---|
isValid | boolean | true if the email is valid, false otherwise. |
formattedEmail | string | a cleaned up email address formatted as lower case and trimmed of spaces, quotes etc. |
Notes
- Library Initialization:
- validator Instance: The function imports the validator.js library’s isEmail method to perform validation.
- Email Validation:
- isEmail Method: Checks if the provided string is a valid email address based on standard email formatting rules.
- Options (Optional): The isEmail method can accept an options object to fine-tune validation parameters, such as allowing specific characters or enforcing stricter rules.
- Return Value:
- Valid Email: Returns { isValid: true } if the email address is valid.
- Invalid Email: Returns { isValid: false } if the email address does not conform to standard formats.
- Error Handling:
- Internal Handling: The isEmail method internally handles parsing errors and edge cases, ensuring reliable validation without the need for explicit error handling in the function.
Example Usage
Description | Input | Output |
|---|---|---|
Valid Email Address | validateEmail("[email protected]") | { isValid: true } |
Invalid Email Address | validateEmail("[email protected]") | { isValid: false } |
Email with Subdomain | validateEmail("[email protected]") | { isValid: true } |
Email with Plus Sign | validateEmail("[email protected]") | { isValid: true } |
Email with Invalid Characters | validateEmail("john.doe@exam!ple.com") | { isValid: false } |
Empty String | validateEmail("") | { isValid: false } |
Script
/**
* Validates an email address using the validator.js library.
*
* @param {string} value - The email address to validate.
* @returns {{
* isValid: boolean,
* validationError?: string
* }} - An object containing the validity of the email and an optional validation error message.
*/
function validateEmail(value) {
const validator = require('validator');
const isValid = validator.isEmail(value.trim());
if (isValid) {
return { isValid };
} else {
return {
isValid: false,
validationError: 'Invalid email address format.',
};
}
}URL
Function
validateURL(value)
Description
The validateURL function is designed to validate and format a given URL string. It ensures that the URL is correctly structured, optionally removes URL parameters, and normalizes the protocol to https:// if it’s absent. This function supports both http and https protocols and returns an object indicating the validity of the URL along with the formatted URL string.
Parameters
Parameter | Type | Description |
|---|---|---|
value | string | The URL string to be validated and formatted. |
removeParams | boolean | (Optional) A flag indicating whether to remove URL parameters (query string) from the URL. Defaults to false if not provided. |
Return Value
Parameter | Type | Description |
|---|---|---|
isValid | boolean | Indicates whether the input URL is valid (true) or invalid (false). |
formattedURL | string or null | The formatted URL string if valid, all lower case, trimmed; otherwise, null. |
Notes
- Trimming Input:
- Removes any leading and trailing whitespace from the input value to ensure accurate validation.
- Protocol Handling:
- Checks if the input URL starts with http:// or https:// (case-insensitive).
- If the protocol is missing, it defaults to adding https:// to promote secure URLs.
- URL Parsing and Validation:
- Utilizes the built-in URL constructor to parse the URL.
- If the URL constructor successfully parses the URL, it’s considered valid.
- If parsing fails (i.e., the URL is invalid), the function catches the error and marks the URL as invalid.
- Formatting:
- Trailing Slashes: Removes any trailing slashes from the URL’s pathname to standardize the format.
- URL Parameters: If removeParams is true, it strips away the query parameters (?query=123) from the URL.
- Hash Preservation: Preserves the hash (#section) if present in the original URL.
- Error Handling:
- Employs try-catch blocks to gracefully handle invalid URLs without causing runtime errors.
Example Usage
Input | Output |
|---|---|
validateURL(" example.com/ ") | {
isValid: true,
formattedURL: "https://example.com"
} |
validateURL("https://example.com/path?query=123", true) | {
isValid: true,
formattedURL: "https://example.com/path"
} |
validateURL("ht!tp://invalid-url") | {
isValid: false,
formattedURL: null
} |
Script
/**
* Validates and formats a given URL string.
*
* @param {string} value - The URL string to be validated and formatted.
* @param {boolean} [removeParams=false] - Optional flag to remove URL parameters (query string).
* @returns {{
* isValid: boolean,
* formattedURL: string | null,
* validationError?: string
* }} An object containing the validity of the URL, the formatted URL string, and an optional validation error message.
*/
function validateURL(value, removeParams = false) {
let trimmedValue = value.trim();
// Ensure the URL starts with http:// or https://
if (!/^https?:\/\//i.test(trimmedValue)) {
trimmedValue = 'https://' + trimmedValue;
}
try {
const url = new URL(trimmedValue);
let formattedURL = `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`;
if (!removeParams && url.search) {
formattedURL += url.search;
}
if (url.hash) {
formattedURL += url.hash;
}
return {
isValid: true,
formattedURL,
};
} catch (error) {
// Determine a user-friendly error message
let errorMessage = 'Invalid URL format.';
// Optionally, use the error message from the URL constructor
if (error instanceof TypeError) {
errorMessage = error.message;
}
return {
isValid: false,
formattedURL: null,
validationError: errorMessage,
};
}
}