2.3.1 • Published 12 months ago

another-validator v2.3.1

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Another Validator npm version License: MIT Coverage Status

Whether you're building a simple form or a complex application, this validator is a valuable tool for validating user input and data.

Features

  • Configurable input requirements, such as minimum length, maximum length, lowercase, uppercase, digits, and special characters, making it easy to customize the validation rules to match your specific needs.
  • Extensible capabilities. You can add custom validation functions for specific use cases, allowing you to easily create validation rules that are tailored to your application's unique requirements.
  • Flexible configuration options, allowing you to specify which validation rules are required and which are optional.
  • Customizable error messages.

Usage

Functions

If you only need to validate a simple condition, for example if the string is a mail or an url you can use a simple function. This package provides a set of functions that you can use to validate input. Go to the functions documentation for more information (is below the validators methods).

Validators

This package provides a set of validators that you can use to validate user input.

  • Validator - Validates a single input, such as a password or a username.
  • NumberValidator - Validates a number.
  • CardValidator - Validates a credit card number (Uses Luhn's Algorithm). It can validate a number of different card types, including Visa, MasterCard, American Express, Discover, etc.
  • SchemaValidator - Validates an object. It can validate multiple inputs at once. You can nest SchemaValidator for complex objects and arrays.
  • ArrayValidator - Validates that each element in an array meets the specified requirements.

Add validations

When you create a new validator, you can specify the validation rules that you want to use. You can also specify the error messages that you want to use for each rule.

If you have specific requirements for your application, you can add custom validation rule. In order to do that you have to create your own validation function. The validation function should return a boolean value. If the function returns true, the input is considered valid. If the function returns false, the input is considered invalid.

Example:

// If no error messages are provided, the default error messages are used
const passwordValidator = new Validator()
  .minLength(5)
  .maxLength(10)
  .requireLowercase("this input requires a lowercase letter")
  .requireUppercase()
  .requireNumber()
  .requireSpecialCharacter()
  .addRule((input) => {
    return !input.includes("example");
  });

const ageValidator = new NumberValidator()
  .min(18)
  .max(65)
  .notNull("this input cannot be null");

const cardValidator = new CardValidator();

const productValidator = new SchemaValidator({
  name: new Validator().notEmpty(),
  price: new NumberValidator().min(0),
  sku: new Validator().fixedLength(10).onlyNumbers(),
});

const productsValidator = new ArrayValidator(productValidator)
  .notEmpty()
  .noDuplicates()
  .comparator((a, b) => a.sku === b.sku);

const schemaValidator = new SchemaValidator({
  username: new Validator().notEmpty(),
  password: passwordValidator, 
  age: ageValidator, 
  card: new CardValidator(), 
  products: productsValidator,
});

schemaValidator.validate(someObject);

Sanitizers

This package offers some sanitizers for strings. You can use them to sanitize user input before validating it.

Available methods

Each validator has three common methods:

  • isValid(inpput) - Returns true if the input meets the requirements, otherwise returns false.
  • validate(input) - Throws an error if the input does not meet the requirements. The error object contains information about all the errors.
  • getErrorMessages(input) - Returns an array of error messages. It does not throw an error.

SchemaValidator and ArrayValidator have a getErrors(input) method that returns an object with the error messages.

You should use getErrors if you want to get detailed information about the errors.

Validator

MethodDescriptionParameters
notEmptyValidates that the input is not empty.message?: string (optional)
notBlankValidates that the input is not blank (contains non-whitespace characters).message?: string (optional)
fixedLengthValidates that the input has a fixed length.length: number, message?: string (optional)
isEmailValidates that the input is a valid email.message?: string (optional)
isUrlValidates that the input is a valid URL.message?: string (optional)
minLengthValidates that the input has a minimum length.length: number, message?: string (optional)
maxLengthValidates that the input has a maximum length.length: number, message?: string (optional)
requireUppercaseValidates that the input contains at least one uppercase character.message?: string (optional)
requireLowercaseValidates that the input contains at least one lowercase character.message?: string (optional)
requireNumberValidates that the input contains at least one number.message?: string (optional)
requireSpecialCharacterValidates that the input contains at least one special character.message?: string (optional)
noWhitespacesValidates that the input contains no whitespace characters.message?: string (optional)
noNumbersValidates that the input contains no numbers.message?: string (optional)
noSpecialCharactersValidates that the input contains no special characters.message?: string (optional)
onlyNumbersValidates that the input contains only numbers.message?: string (optional)
noRepeatedCharactersValidates that the input contains no repeated characters.message?: string (optional)
onlyCharactersValidates that the input contains only alphabetical characters.message?: string (optional)
addRuleAdds a custom validation rule. The validation function should return a boolean value. If the function returns true, the input is considered valid. If the function returns false, the input is considered invalid.(input?) => boolean, message?: string (optional)

When setting a max or min these values are inclusive.

NumberValidator

MethodDescriptionParameters
minSets the minimum allowed value for the input.value: number, message?: string (optional)
maxSets the maximum allowed value for the input.value: number, message?: string (optional)
isNegativeChecks if the input is negativemessage?: string
isPositiveChecks if the input is positive (bigger than 0)message?: string
isNonNegativeChecks if the input is non-negative (i.e., zero or positive)message?: string
addRuleAdds a custom validation rule. The validation function should return a boolean value. If the function returns true, the input is considered valid. If the function returns false, the input is considered invalid.(input?) => boolean, message?: string (optional)

When setting a max or min these values are inclusive.

CardValidator

If it is used with SchemaValidator it will only validate the card number.

MethodDescriptionParameters
isCardProviderValidChecks if the card number is valid for the given card providercardNumber: string, provider: CardProvider
validateExpirationValidates the expiration date of a credit cardexpiration: string
validateValidates the credit card input based on the card number, provider, and expiration date. The date must have the format (MM/YY)input: {cardNumber: string, provider?: CardProvider, expirationDate?: string} | string
getErrorMessagesReturns an array of error messages based on the card number, provider, and expiration dateinput: {cardNumber: string, provider?: CardProvider, expirationDate?: string} | string
addRuleAdds a custom validation rule. The validation function should return a boolean value. If the function returns true, the input is considered valid. If the function returns false, the input is considered invalid.(input?) => boolean, message?: string (optional)

If you are using TypeScript, you must use the CardProvider enum to specify the card provider

Providers:

  • Visa
  • MasterCard
  • AmericanExpress
  • Discover
  • JBC
  • DinersClub
  • Maestro
  • UnionPay
  • TarjetaNaranja

SchemaValidator

MethodDescriptionParameters
getErrorsReturns an object containing error messages for the input object, with keys corresponding to the fields in the schema.input: any

Usage example:

const validator = new SchemaValidator({
    name: new Validator().notBlank().minLength(3),
    payment: new SchemaValidator({
        sku: new Validator().fixedLength(4).onlyNumbers(),
        price: new NumberValidator().min(0, "cannot be 0 or less"),
        cardNumber: new CardValidator(),
    }),
});

const input = {
    name: ' ',
    payment: {
        cardNumber: '1234',
        sku: '123',
        price: -1,
    },
}

const errors = validator.getErrors(input);

console.log(errors);
/* If no error messages are provided, the default error messages are used:
{
  name: [
    'the value cannot be empty',
    'the value does not meet the minimum length'
  ],
  payment: {
    sku: [ 'the value does not meet the fixed length' ],
    price: [ 'cannot be 0 or less' ],
    cardNumber: [ 'Invalid card number' ]
  }
}
*/

ArrayValidator

MethodDescriptionParameters
minLengthSets the minimum allowed length for the input array.value: number, message?: string (optional)
maxLengthSets the maximum allowed length for the input array.value: number, message?: string (optional)
notEmptyRequires the input array to be non-empty.message?: string (optional)
noDuplicatesRequires the input array to have no duplicate elements.message?: string (optional)
comparatorSets the custom comparator function to be used for checking duplicates.func: (a: any, b: any) => boolean
addRuleAdds a custom validation rule. The validation function should return a boolean value. If the function returns true, the input is considered valid. If the function returns false, the input is considered invalid.(input?) => boolean, message?: string (optional)

If you use noDuplicates without setting a custom comparator function, the validator will use the === operator to check for duplicates. When setting a max or min these values are inclusive.

Usage example:

import { ArrayValidator, CardValidator, NumberValidator, SchemaValidator, Validator } from "another-validator";

const nameValidator = new Validator().minLength(2).maxLength(20).notEmpty();

const validator = new ArrayValidator(nameValidator)
    .minLength(2)
    .maxLength(5)
    .notEmpty()
    .noDuplicates();


const input = ["John", "Doe", "John", ""];

const errors = validator.getErrorMessages(input);

console.log(errors);
/* If no error messages are provided, the default error messages are used:
[
  'the array must not contain any duplicates',
  'the value does not meet the minimum length',
  'the value cannot be empty'
]
*/

Functions

String validations

MethodDescriptionParameters
isEmailChecks if is a valid email addressemail: string
isUrlChecks if is a valid URL. If strict = true, the url must have a valid protocol (https, http), by default this value is falseurl: string, strict?: boolean
containsOnlyNumbersChecks if contains only numbersinput: string
containsOnlyLettersChecks if contains only lettersinput: string
containsUppercaseChecks if contains at least one uppercase letterinput: string
containsLowercaseChecks if contains at least one lowercase letterinput: string
containsSpecialCharacterChecks if contains at least one special characterinput: string
containsNumbersChecks if contains at least one numberinput: string
notContainsNumbersChecks if does not contain any numbersinput: string
notContainsSpecialCharacterChecks if does not contain any special charactersinput: string
notContainsWhitespaceChecks if does not contain any whitespaceinput: string
isIPChecks if is a valid IP addressinput: string
isISO8601Checks if is a valid ISO 8601 date or datetime stringdateString: string
isBTCAddressChecks if is a valid Bitcoin addressaddress: string
isETHAddressChecks if is a valid Ethereum addressaddress: string
isJWTChecks if is a valid JSON Web Token (JWT)token: string
isNotBlankChecks if is not blank (contains non-whitespace chars)input: string
hasLengthChecks if has a specific lengthinput: string, length: number
isNotEmptyChecks if is not emptyinput: string
containsRepeatedCharsChecks if contains any repeated charactersstr: string

Credit Card validations

MethodDescriptionParameters
isAValidCreditCardNumberChecks if a string is a valid credit card number using Luhn algorithmcardNumber: string
isExpirationDateValidChecks if a credit card expiration date is valid. The format must be (MM/YY)expirationDate: string
isCreditCardNumberAndProviderValidChecks if a credit card number is valid for a given card providercardNumber: string, provider: CardProvider
isCreditCardValidChecks if a credit card has a valid number, provider, and expiration date{cardNumber: string, provider: CardProvider, expirationDate: string}

Providers:

  • Visa
  • MasterCard
  • AmericanExpress
  • Discover
  • JBC
  • DinersClub
  • Maestro
  • UnionPay
  • TarjetaNaranja

Example:

isCreditCardValid({
  cardNumber: "4111111111111111", 
  provider: CardProvider.Visa, 
  expirationDate: "12/03"
}); 

Date validations

MethodDescriptionParams
isPastDateCheck if a date is in the pastdate: Date
isFutureDateCheck if a date is in the futuredate: Date
isSameDayCheck if two dates are on the same daydate1: Date, date2: Date
isSameMonthCheck if two dates are in the same monthdate1: Date, date2: Date
isSameYearCheck if two dates are in the same yeardate1: Date, date2: Date
isLeapYearDetermine if a year is a leap yearyear: number
isValidDateValidate a date objectdate: Date
isDateInRangeCheck if a date is within a specified rangedate: Date, startDate: Date, endDate: Date

Sanitizers

MethodDescriptionParameters
keepAlphanumericRemoves all non-alphanumeric characters from the input stringinput: string
keepOnlyNumbersKeeps only numeric characters in the input stringinput: string
keepOnlyCharactersKeeps only alphabetic characters in the input stringinput: string
camelCaseToSnakeCaseConverts a camelCase string to a snake_case stringinput: string
snakeCaseToCamelCaseConverts a snake_case string to a camelCase stringinput: string
normalizeSpanishInputRemoves tildes from Spanish vowels and replaces ñ with n in the input stringinput: string

TypeScript Support

This library is written in TypeScript and includes type definitions.

Contributing

Contributions are welcome! Please feel free to submit a pull request, report an issue, or suggest new features.

License

This project is licensed under the MIT License.

2.3.1

12 months ago

2.3.0

1 year ago

2.2.0

1 year ago

2.1.0

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.2.1

1 year ago

1.2.0

1 year ago

1.1.0

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago