1.0.3 • Published 1 year ago

simple-string-validator v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

Easy input validation with form validator

This library will help you validate any strings (emails, passwords, URLs, etc) and show an error if the validation fails.

Features:

  • Small size.
  • No extra npm dependecies.
  • Typescript support.
  • Full test coverage.
  • Support all platforms.

Table of contents

Quick start

For start using:

npm i simple-string-validator

or

yarn add simple-string-validator

Usage example

React:

import React, { useState } from 'react';
import validate from 'simple-string-validator';

function InputValidation() {
  const [email, setEmail] = useState('');
  const [emailErrors, setEmailErrors] = useState<string[] | null>();

  const submitForm = (e: React.ChangeEvent<HTMLFormElement>) => {
    e.preventDefault();
    setEmailErrors(null);
    const { errors } = validate(email, { isEmail: true, required: true });
    if (errors) {
      setEmailErrors(errors);
      return;
    }
    //submit form logic
  };

  return (
    <form onSubmit={submitForm}>
      <h1>Enter your email to subscribe.</h1>
      <input value={email} onChange={(e) => setEmail(e.target.value)} />
      {emailErrors &&
        emailErrors.map((error) => {
          return <p>{error}</p>;
        })}
      <button>Submit</button>
    </form>
  );
}

export default InputValidation;

You could get all the validation errors from the "errors" array.

You could also provide your custom error message (see accepted parameters below).

Settings

ParameterTypeDescription
maxLengthnumberSets the maximum allowed string length.
minLengthnumberSets the minimum allowed string length.
requiredbooleanIndicates whether this string is required
numbersOnlybooleanA flag that indicates that only numbers should be contained in the string.
lettersOnlybooleanA flag that indicates that only letters should be contained in the string.
lettersAndNumbersOnlybooleanA flag that indicates that only numbers and letters should be contained in the string. Special characters are not allowed.
case"lower", "upper", "both required"Sets the case in which the string should be
containSpecialCharactersbooleanIndicates that the string must contain special characters.
isEmailbooleanChecks if a string is an email
isURLbooleanChecks if a string is an URL
errorMessagestringAllows you to set a custom error message that will be displayed if the string fails validation.

Custom error messages example:

const { errors } = validate(email, {
      isEmail: true,
      required: true,
      errorMessage: 'Please, provide correct email'
    })

Typescript

This library has full Typescript support.

Bug reporting

You could send it to achekhovskoi@gmail.com or open an issue on https://github.com/ArtemChekhovskoi/form-validate/issues.

License

ISC Licensed. Artem Chekhvskoi, 2023.

Keywords

validate form inputs string validation validator password email