Skip to content

Repository files navigation

validate-form

build statusNPM versionCoverage StatusDavid Dependency Status

browser support

Simple functional form validation

Example

varValidator=require("validate-form")vartruthy=require("validate-form/truthy")varisEmail=require("validate-form/email")varisCreditCard=require("validate-form/credit-card")varrange=require("validate-form/range")varmatch=require("validate-form/match")varmemberOf=require("validate-form/member-of")varlist=require("validate-form/list")varvalidDate=/^\d\d\d\d\/\d\d$/varcountries=["US-en","UK-en","BR-pt", ...]varvalidate=Validator({firstName: [truthy()],lastName: [truthy("Custom message: The %s field is required")],email: [truthy(),isEmail("Please ensure that you enter valid email")],cardNumber: [isCreditCard()],cvv: [range(3,4)],expirationDate: [match(validDate)],country: [memberOf(countries,"enter valid country code")],interest: [list({min: 3,content: [truthy()]})]})

Creating your own validators

You can use custom functions as validators. A validator function takes the value to validate as an argument, the key for that value and the parent object that the value is on.

You can use the key to make more readable validation errors and you can use the parent to do validation logic across multiple properties

A validator should either return nothing or an error or an array of errors, an error in this case is { message: String, type: String }. The type is useful if you want to show custom error messages in the UI, then you can ignore the message and use a custom error message for each type of validation error.

varValidator=require("validate-form")varvalidate=Validator({name: [functionisValidName(value,key,parent){varmessage=""if(typeofvalue!=="string"){message=key+" should be a string"}elseif(value.length<4){message=key+" should be at least 4 characters"}if(message){return{message: message,type: "invalidName"}}}]})

Docs

typeAlmostValidateError := {
type: ValidateErrorType, message: String
}
typePossibleValidateError = Array<AlmostValidateError> |
AlmostValidateError | nulltypeValidator := (value: Any, key: String, parent: Object) =>PossibleValidateErrortypeValidateErrorType := "creditCard" | "email" | "length" |
"match" | "max" | "memberOf" | "min" | "range" | "truthy" | "type"typeValidateError := {
attribute: String,
message: String,
type: ValidateErrorType
}
validate-form := (Object<String, Array<Validator>>) =>Array<ValidationError>| null
validate-form/add-error := (errors: Array<ValidationError>, key: String,
maybeError: PossibleValidateError) =>Array<ValidationError>

Installation

npm install validate-form

Contributors

  • Raynos

MIT Licenced

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages