@rohitninawe/validation
v0.0.8
Published
Validate the code.
Downloads
6
Maintainers
Readme
@rohitninawe/validation
Validate the code as much as possible.
Install
Using npm:
npm install @rohitninawe/validation
or using yarn:
yarn add @rohitninawe/validation
Usage
import { safeArray, isValidEmail } from '@rohitninawe/validation';
safeArray()
If the parameter is not an array, safeArray() will return an empty array to prevent a crash, for instance when using the .map() method.
Examples
safeArray([2, 3, 4, "git", {"name": "John Smith"}])
// [2, 3, 4, "git", {"name": "John Smith"}]
safeArray("[1, 2, 3]")
// [1, 2, 3]
safeArray(undefined)
// []
safeArray(123)
// []
safeArray("")
// []
Pro Tip
If you're unsure whether a key or index exists, always use optional chaining. Example:
let response = null; // expected output => {"users": {"transaction":[]} };
let transaction = response.users.transaction;
//Uncaught TypeError: Cannot read properties of null (reading 'users')
transaction.map(item => item); //Error
//Using Optional Chaining 🤔👇
let transaction = response?.users?.transaction; //returns undefined
transaction.map(item => item);
//Uncaught TypeError: Cannot read properties of undefined (reading 'map')
//Optional Chaining + safeArray 😎
let transaction = response?.users?.transaction; //returns undefined
safeArray(transaction).map(item => item); //returns an empty array [].
isValidEmail()
Checks the email's valid format
Examples
isValidEmail("[email protected]")
// true
isValidEmail("lorem ipsum")
// false
isValidEmail(""); //or any falsy value
// false