📜  validator.js github - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:33.542000             🧑  作者: Mango

Validator.js - Github Repository

Validator.js is a JavaScript library for validating and sanitizing user input. It provides a simple and easy-to-use API for validating different types of data, such as email addresses, phone numbers, URLs, and more.

Features
  • Simple and easy-to-use API
  • Support for validating different types of data
  • Customizable error messages
  • Chainable validation rules
  • Built-in sanitization functions
Installation

You can install Validator.js using npm:

npm install validator

Alternatively, you can include the library in your HTML file using a script tag:

<script src="https://cdn.jsdelivr.net/npm/validator@13.6.0/dist/validator.min.js"></script>
Usage

To use Validator.js, you first need to import or include the library in your project:

const validator = require('validator');

Or

<script src="validator.min.js"></script>

Once you have imported or included the library, you can start using its API to validate and sanitize user input:

if (validator.isEmail('foo@example.com')) {
  console.log('Valid email address');
} else {
  console.log('Invalid email address');
}

This example validates if a given email is valid and returns a message accordingly.

Validator.js provides many other validation and sanitization functions that you can use in your project. A few examples are:

  • isEmail()
  • isURL()
  • isNumeric()
  • isAlpha()
  • isLength()
  • normalizeEmail()
  • escape()
Custom Error Messages

Validator.js allows you to customize the error messages that are returned when a validation rule fails. You can do this by passing a custom error message as the second argument to the validation function:

if (validator.isEmail('foo@bar', {message: 'Please enter a valid email address'})) {
  console.log('Valid email address');
} else {
  console.log('Invalid email address');
}

This example customizes the error message returned when the email address is invalid.

Chainable Validation Rules

You can also chain multiple validation rules together using a fluent interface:

if (
  validator.isEmail('foo@example.com').isLength({min: 10}).isNumeric()
) {
  console.log('Valid input');
} else {
  console.log('Invalid input');
}

This example chains three validation rules together to validate an email address that is at least 10 characters long and comprises of numeric characters.

Conclusion

Validator.js is a powerful JavaScript library for validating and sanitizing user input. It provides a simple and easy-to-use API for validating different types of data and customizing error messages. If you want to ensure the input provided by your users is valid and safe, give Validator.js a try!