Gathering detailed insights and metrics for form-validation-react
Gathering detailed insights and metrics for form-validation-react
Gathering detailed insights and metrics for form-validation-react
Gathering detailed insights and metrics for form-validation-react
react-hook-form
Performant, flexible and extensible forms library for React Hooks
@chakra-ui/form-control
React component to provide validation states to form fields
formik
Build forms in React, without the tears
@hookform/resolvers
React Hook Form validation resolvers: Yup, Joi, Superstruct, Zod, Vest, Class Validator, io-ts, Nope, computed-types, TypeBox, arktype, Typanion, Effect-TS and VineJS
form-validation-react is an easy-to-use npm library that enables developers to add validation rules to form inputs in React. It supports required fields, email formats, and custom rules with various validation functions and options that can be tailored to specific needs.
npm install form-validation-react
Typescript
Module System
Node Version
NPM Version
76.4
Supply Chain
99.1
Quality
76.2
Maintenance
100
Vulnerability
100
License
JavaScript (58.76%)
TypeScript (41.13%)
HTML (0.11%)
Built with Next.js • Fully responsive • SEO optimized • Open source ready
Total Downloads
6,556
Last Day
1
Last Week
10
Last Month
93
Last Year
1,180
MIT License
3 Stars
111 Commits
2 Watchers
6 Branches
2 Contributors
Updated on Jul 09, 2024
Latest Version
1.5.0
Package Id
form-validation-react@1.5.0
Unpacked Size
346.36 kB
Size
36.79 kB
File Count
9
NPM Version
8.3.0
Node Version
16.13.1
Published on
Apr 19, 2023
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
900%
10
Compared to previous week
Last Month
244.4%
93
Compared to previous month
Last Year
-17.5%
1,180
Compared to previous year
Check this website - reactvalidator.tech
You can install the package using npm or yarn:
1 npm i form-validation-react 2
1 yarn add form-validation-react 2
To use the library, import it in your React component:
1 import ValidateForm from "form-validation-react" 2
Then, wrap your form with
1<ValidateForm 2 onSubmit={(event)=> { 3 console.log("Form submitted",event); 4 }} 5 errorElement="#error_show_element" // optional 6 rules={{ 7 // add the rules here 8 }} 9> 10 11 <form> 12 <h1 id="error_show_element" > // The error message will appear in this element </h1> 13 <input type="text" required /> 14 </form> 15 16</ValidateForm> 17
onSubmit
: This function executes when click on submit button with no validation errors. If you not call this function the form will submit when no validation errors1validateRequired: { 2 3 action: "show_error_message", 4 message: "fill all required fields", 5 applyOnly:["name","password"] // checking only this inputs are filled 6 notvalidated: (notFilledInputs) => { 7 console.log("Not filled required inputs",notFilledInputs); 8 } 9 onsuccess:()=> { 10 console.log("All required fields are filled"); 11 } 12 13} 14
If a required input is not filled, the rule will return a callback with an array of the not-filled inputs. You can add the action input_red_border
to change the border color of the not-filled inputs to red.
Key | Type | Parameter | Optional |
---|---|---|---|
action | string | input_red_border ,show_error_message ,both | no |
message | string | Message | yes |
applyOnly | array | Name of the inputs | yes |
notvalidated | callback function | notFilledInputs | yes |
onsuccess | callback function | no params | yes |
password
. because password input is not readable or writable for security reasons. work only with text
,number
type1ValidateMinMax: { 2 3 when: "typing" 4 message : { 5 min: "Full name must be at least 4 characters", 6 max: "Full name must be at most 8 characters" 7 }, 8 exceedsMax: ()=> { 9 console.log("Maximum length exceeded"); 10 }, 11 exceedsMin: ()=> { 12 console.log("Minimum length exceeded"); 13 } 14 onsuccess:(validatedInput)=> { 15 console.log("Length is in range of :",validatedInput); 16 } 17 18} 19 20
1 <input min={4} max={8} type="number" required /> 2
the min
in message object is when exceeded minimum the message will show.
the max
in message object is when exceeded maximum the message will show
Key | Type | Parameter | Optional |
---|---|---|---|
when | string | typing ,onblur | no |
message | object | Messages | yes |
exceedsMax | callback function | when exceeded max | yes |
exceedsMin | callback function | when exceeded min | yes |
onsuccess | callback function | validatedInput | yes |
1ValidateEmail: { 2 3 type: "yahoo", 4 emailInput: "my_email", 5 message: "Please enter a valid yahoo email", 6 onsuccess: () => console.log("Email is valid"), 7 invalid: () => console.log("Email is invalid"), 8 when: "onblur", 9 10}
1<input name="my_email" type="email" required />
type:
a string representing the type of email being validated (personal, business, yahoo, gmail, hotmail, aol, isp, education, government, nonprofit, international, domain-specific, or alias)emailInput:
a string representing the name of the input element in the form that contains the email addressmessage:
a string representing the error message to be displayed if the email is invalidonsuccess:
a callback function to be executed if the email is validinvalid:
a callback function to be executed if the email is invalidwhen:
a string specifying when the validation should occur (onblur or typing)1validatePattern:{ 2 3 input: 'email', 4 pattern: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/, 5 type: 'regex', 6 when: 'typing', 7 allowEmpty: false, 8 onsuccess: (inputElement) => console.log('Validation succeeded!’), 9 invalid: () => console.log('Validation failed!’), 10 errorMessage: 'Please enter a valid email address.' 11 12}
1validatePattern:{ 2 pattern: /^\S+@\S+\.\S+$/, 3 modifiers: 'i', 4 input: 'email', 5 type: 'regex', 6 when: 'typing', 7 errorMessage: 'Please enter a valid email address', 8}
1validatePattern:{ 2 pattern: '*.com', 3 type: 'wildcard', 4 modifiers: 'i', 5 input: 'email-input', 6 when: 'typing', 7 errorMessage: 'Please enter an email address ending in .com' 8}
1validatePattern:{ 2 pattern: /^\S+@\S+\.\S+$/, 3 modifiers: 'i', 4 input: 'email', 5 type: 'regex', 6 when: 'typing', 7 allowEmpty: true, 8}
input
(required): The name of the input field to validate.pattern
(required): A string representing the pattern to validate against. It can be a regular expression or a wildcard pattern.type
(required): A string representing the type of pattern used. It can be either "regex"
or "wildcard"
.modifiers
(optional): A string representing the modifiers for the regular expression. Only used when type
is "regex"
.when
(optional): A string representing the event that triggers the validation. It can be either "onblur"
or "typing"
. If not specified, "onblur"
is used by default.allowEmpty
(optional): A boolean value indicating whether empty input should be considered valid. If not specified, false
is used by default.onsuccess
(optional): A function that is called when the validation succeeds.invalid
(optional): A function that is called when the validation fails.errorMessage
(optional): A string representing the error message to display when the validation fails.We provide two different patterns - a regular expression pattern and a wildcard pattern - along with options for case-insensitivity (modifiers: 'i'
) and custom error messages.
We also use the allowEmpty
option to allow the input to be empty, which can be useful for optional fields.
1ValidatePhone: { 2 3 phoneInput: 'phone_input', // required 4 countryCode: 'US', // required 5 when: 'onblur', // required 6 7 onsuccess: (input) => console.log(`${input.value} is a valid phone number`), 8 invalid: () => console.log('Invalid phone number'), 9 message: 'Please enter a valid US phone number', 10 isLandlineNumber: (isLandline) => console.log(`Is a landline: ${isLandline}`), 11 isMobileNumber: (isMobile) => console.log(`Is a mobile: ${isMobile}`) 12 13}
1<input type="number" name="phone_input" />
phoneInput
: the name of the input field to validate.countryCode
: an optional country code to use in the validation process.when
: the event to trigger the validation process. Can be set to either "onblur" or "typing".onsuccess
: a function to execute when the validation is successful.invalid
: a function to execute when the validation is unsuccessful.message
: an error message to display when the validation is unsuccessful.isLandlineNumber
: a function that receives a boolean value indicating if the input is a landline number.isMobileNumber
: a function that receives a boolean value indicating if the input is a mobile number.1ValidateNumber: { 2 3 input: "my-number-input", // required 4 when: "typing", // required 5 6 min: 0, 7 max: 100, 8 decimalPlaces: 2, 9 allowNegative: false, 10 integersOnly: false, 11 base: 10, 12 customErrorMessages: { 13 invalidNumber: "Invalid number", 14 range: "Number must be between 0 and 100", 15 decimalPlaces: "Number must have no more than 2 decimal places", 16 negative: "Negative numbers are not allowed", 17 integersOnly: "Only integers are allowed", 18 base: "Number must be in base 10", 19 }, 20 onsuccess: () => { 21 console.log("Validation succeeded!"); 22 }, 23 invalid: () => { 24 console.log("Validation failed!"); 25 } 26 27},
1<input type="number" name="my-number-input" />
min
(optional): The minimum value of the number.max
(optional): The maximum value of the number.input
: The name of the input field to validate.when
: The timing of the validation. Valid values are "onblur" and "typing".decimalPlaces
(optional): The number of decimal placesallowNegative
(optional): A boolean value indicating whether negative numbers are allowed. Defaults to true.integersOnly
(optional): A boolean value indicating whether the number must be an integer. Defaults to false.base
(optional): The base of the number.customErrorMessages
(optional): An object containing custom error messages. Valid properties are invalidNumber, range, decimalPlaces, negative, integersOnly, and base.onsuccess
(optional): A callback function to execute when validation succeeds.invalid
(optional): A callback function to execute when validation fails.1ValidateInteger: { 2 when: 'onblur', // or 'typing' 3 input: 'age', // name of the input element to validate 4 minValue: 0, 5 maxValue: 100, 6 uniqueValues: [10, 20, 30], 7 positiveOnly: true, 8 evenOnly: true, 9 divisibleBy: 5, 10 invalid: () => { 11 console.log('Invalid input'); 12 }, 13 customErrorMessages: { 14 notANumber: 'Please enter a number', 15 notAnInteger: 'Please enter an integer', 16 outOfRange: 'Please enter a value between 0 and 100', 17 notUnique: 'Please enter a unique value', 18 notPositive: 'Please enter a positive value', 19 notEven: 'Please enter an even value', 20 notDivisible: 'Please enter a value divisible by 5', 21 }, 22 },
when
(required): A string indicating when to run the validation. Possible values are 'onblur' (validate on blur) and 'typing' (validate while typing).
input
: (required) A string representing the name of the input element to validate.
minValue
(optional): An integer representing the minimum value that the input element can have.
maxValue
(optional): An integer representing the maximum value that the input element can have.
uniqueValues
(optional): An array of integers representing values that should be unique.
positiveOnly
(optional): A boolean indicating whether the input element can only have positive values.
evenOnly
(optional): A boolean indicating whether the input element can only have even values.
divisibleBy
(optional): An integer representing a number by which the input element should be divisible.
invalid
(optional): A function to call if the input element is invalid.
customErrorMessages
(optional): An object containing custom error messages to display.
1ValidateFloat: { 2 3 when: 'onblur', // when to validate input - onblur or typing 4 input: 'input-name', // name of input field to validate 5 6 required: true, // whether the input is required or not 7 min: 0, // minimum value for input 8 max: 100, // maximum value for input 9 precision: 2, // maximum number of decimal places allowed 10 customErrorMessages: { 11 required: 'This field is required!', 12 invalid: 'Please enter a valid number!', 13 min: 'Please enter a number greater than or equal to {min}!', 14 max: 'Please enter a number less than or equal to {max}!', 15 precision: 'Please enter a number with at most {precision} decimal places!', 16 }, 17 18},
1ValidateDate: { 2 3 when: 'typing', // required 4 input: 'dob', // required 5 6 minDate: new Date('2000-01-01'), 7 maxDate: new Date('2023-03-07'), 8 allowOnlyBusinessDay: true, 9 allowOnlyWeekend: false, 10 customFormat: 'dd-MM-yyyy', 11 timeZone: 'Asia/Kolkata', 12 customErrorMessages: { 13 invalidDate: 'Invalid date format. Please enter a valid date.', 14 minDate: 'Date should not be earlier than 1st January 2000.', 15 maxDate: 'Date should not be later than 7th March 2023.', 16 businessDay: 'Selected date is not a business day.', 17 notWeekend: 'Selected date is not a weekend.', 18 invalidFormat: 'Date format is not valid. Please enter the date in dd-MM-yyyy format.', 19 invalidTimeZone: 'Invalid time zone. Please enter a valid time zone.', 20 } 21 22 }
when
The when rule determines when the validation should occur. It can be set to "typing" or "onblur".
input
The input rule specifies the name of the input field to validate.
minDate
The minDate rule specifies the minimum date that is allowed. Dates before this minimum date are considered invalid.
maxDate
The maxDate rule specifies the maximum date that is allowed. Dates after this maximum date are considered invalid.
allowOnlyBusinessDay
The allowOnlyBusinessDay rule determines whether or not only business days are allowed. Business days are weekdays (Monday to Friday).
allowOnlyWeekend
The allowOnlyWeekend rule determines whether or not only weekends are allowed. Weekends are Saturday and Sunday.
customFormat
The customFormat rule specifies the custom format for the date. If not specified, the date will be validated in the default format.
timeZone
The timeZone rule specifies the time zone for the date. If not specified, the date will be validated in the local time zone.
customErrorMessages
The customErrorMessages rule allows you to specify custom error messages for different validation rules. If not specified, default error messages will be used.
1ValidateTime: { 2 3 when: 'onblur', // required 4 input: 'time-input', // required 5 6 customErrorMessages: { 7 invalidFormat: 'Invalid time format, please enter time in the format HH:mm', 8 invalidRange: 'Time is out of range, please enter a valid time', 9 invalidInterval: 'Time is not within the specified interval, please enter a valid time', 10 invalidTimezone: 'Invalid timezone, please enter a valid timezone', 11 }, 12 timeRange: { 13 startTime: '08:00', 14 endTime: '17:00', 15 }, 16 timeInterval: { 17 startInterval: 480, 18 endInterval: 1020, 19 }, 20 timezone: 'America/New_York' 21 22}
when
: A string value that specifies when to perform the validation. It can be either 'typing' or 'onblur'.
input
: A string value that specifies the name of the input element to validate.
customErrorMessages
: An object that specifies custom error messages to use for the validation.
timeRange
: An object that specifies a time range that the input value should fall within.
timeInterval
: An object that specifies an interval that the input value should fall within.
timezone
: A string value that specifies the timezone to use for the validation. If not specified, the local timezone is used.
1 2ValidateUrl: { 3 4 when: "typing", // required 5 input: "urlInput", // required 6 7 CustomErrorMessages: { 8 invalidUrl: "Invalid URL", 9 invalidProtocol: "Invalid Protocol", 10 invalidDomain: "Invalid Domain", 11 invalidIpAddress: "Invalid IP Address", 12 inaccessibleUrl: "Inaccessible URL", 13 invalidCharacters: "Invalid Characters", 14 protocolNotAllowed: "Protocol not allowed", 15 }, 16 checkUrl: true, 17 checkProtocol: true, 18 checkDomain: true, 19 checkIpAddress: true, 20 checkInAccessibleUrl: true, 21 checkCharacters: true, 22 protocols: ["https", "http"], 23 24 }, 25
when
: When to validate the URL input. This can be either "typing" or "onblur".
input
: The name of the input field to validate.
CustomErrorMessages
: Custom error messages for each type of validation error. This is an optional property.
checkUrl
: Whether to check the URL for well-formedness.
checkProtocol
: Whether to check the protocol of the URL.
checkDomain
: Whether to check the domain name of the URL.
checkIpAddress
: Whether to check the IP address of the URL.
checkInAccessibleUrl
: Whether to check if the URL is accessible.
checkCharacters
: Whether to check for invalid characters in the URL.
protocols
: An array of allowed protocols. This is used when checkProtocol is set to true. If this property is not specified, any protocol is allowed.
1 2ValidateCreditCard: { 3 4 when: "typing", // required 5 cardNumber: "card-input", // required 6 7 allowedCards: ["Visa", "Mastercard"], 8 expirationDate: "expiration-date", 9 cvv: "cvv", 10 billingZip: "billing-zip", 11 customErrorMessages: { 12 invalidCardNumber: "Invalid credit card number", 13 onlyAllowedCards: "Only Visa and Mastercard are allowed", 14 invalidExpirationDate: "Invalid expiration date", 15 invalidCVV: "Invalid CVV code", 16 invalidBillingZip: "Invalid billing zip code", 17 }, 18 getCardType: (cardType) => console.log(cardType); // Visa 19 20 } 21
when
- When to validate. This can be either "typing" or "onblur".
allowedCards
- An optional array of strings that contains the card types that are allowed. If this property is not set, all card types are allowed.
cardNumber
- A string that contains the name of the input element that contains the credit card number.
expirationDate
- A string that contains the name of the input element that contains the expiration date.
cvv
- A string that contains the name of the input element that contains the CVV code.
billingZip
- A string that contains the name of the input element that contains the billing zip code.
customErrorMessages
- An optional object that contains custom error messages for each validation rule. The keys should match the validation function names, and the values should be strings that represent the error message.
getCardType
- An optional function that can be used to determine the card type based on the credit card number.
Here is an example of how to use the library in a ReactJS component:
1import React from "react"; 2import ValidateForm from "form-validation-react"; 3 4function App() { 5 return ( 6 <div className="App"> 7 8 <ValidateForm 9 rules={{ 10 11 validateRequired: { 12 action: "input_red_border", 13 notvalidated: (notFilledInputs) => { 14 console.log("Not filled required inputs", notFilledInputs); 15 } 16 }, 17 18 ValidateMinMax: { 19 when: "onblur" 20 message : { 21 min: "Full name must be at least 4 characters", 22 max: "Full name must be at most 8 characters" 23 } 24 } 25 26 }} 27 > 28 <form> 29 <input min={4} max={8} type="text" name="full_name" required /> 30 <input required type="text" name="full_name" /> 31 <input required type="email" name="email" /> 32 <button type="submit">Submit</button> 33 </form> 34 </ValidateForm> 35 36 </div> 37 ); 38} 39 40export default App; 41 42
No vulnerabilities found.