The validateName
Function is used to validate names. It returns an object with two properties: 'isValid' (boolean) and 'errorMsg' (string). The 'errorMsg' property will contain the error message if the name is invalid, or it will be null if the name is valid.
function validateName(
name: string,
{
minLength?: number,
maxLength?: number,
errorMsg?: string[]
}
): { isValid: boolean, errorMsg: string | null };
name
(string) - The name to be validated.minLength
(number) - [optional] The minimum length allowed for the name. Default value: 1.maxLength
(number) - [optional] The maximum length allowed for the name. Default value: 20.errorMsg
(string[]) - [optional] - An array of error messages to customize the response. If not provided, the function will use default error messages.[
'Invalid value passed',
'Name cannot contain numbers',
'Name cannot contain special characters',
'This name is not valid',
'Name too big, try again',
'Unknown error',
]
const result1 = validateName("John", {
minLength: 2,
maxLength: 20,
});
console.log(result1);
// Output: { isValid: true, errorMsg: null }
const result2 = validateName("J0hn");
console.log(result2);
// Output: { isValid: false, errorMsg: 'Name cannot contain numbers' }
const result3 = validateName("John$");
console.log(result3);
// Output: { isValid: false, errorMsg: 'Name cannot contain special characters' }
const result4 = validateName("NameWithTwentyOneCharacters");
console.log(result4);
// Output: { isValid: false, errorMsg: 'Name too big, try again' }