The validateUsername
function is used to validate usernames. It returns an object with two properties: "isValid" (boolean) and "errorMsg" (string). The "isValid" property will be true if the username meets the specified criteria, and "errorMsg" will contain the error message if the username is invalid, or it will be null if the username is valid.
The function can be imported using ES6 syntax from the "multiform-validator" package:
import { validateUsername } from 'multiform-validator';
Alternatively, you can import the function using CommonJS syntax with require
(Node.js):
const { validateUsername } = require('multiform-validator');
interface OptionsParams {
minLength?: number;
maxLength?: number;
errorMsg?: (string | null)[];
}
const defaultOptionsParams: OptionsParams = {
minLength: 1,
maxLength: infinity,
errorMsg: defaultErrorMsg,
};
function validateUsername(
username: string,
{ minLength, maxLength, errorMsg }: OptionsParams = defaultOptionsParams,
): { isValid: boolean, errorMsg: string | null };
username
(string) - The username to be validated.minLength
(number) [optional] - The minimum length of the username. Default is 1.maxLength
(number) [optional] - The maximum length of the username. Default is Infinity.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',
'Username too short',
'This username is too long',
'Username cannot contain spaces',
'Cannot start with a number',
'Cannot contain only numbers',
'Unknown error'
]
const result1 = validateUsername("User999", {
minLength: 8,
maxLength: 20,
});
console.log(result1);
// Output: { isValid: true, errorMsg: null }
const customErrorMsg = ["Custom error 1", "Custom error 2"];
const result2 = validateUsername("User999", {
minLength: 8,
maxLength: 20,
errorMsg: customErrorMsg,
});
console.log(result2);
// Output: { isValid: false, errorMsg: 'Username too short' }