@sksuri/form-blur-validation-hook
v2.0.0
Published
React hooks for form blur validation
Downloads
2
Readme
Form Validation on Blur with React
This project demonstrates form validation in a React application using TypeScript.
Usage
Install the package in your project:
npm install @sksuri/form-blur-validation-hook
Example: Using the useFormBlurValidation Hook
// Validation rules object
const validationRules = [
{
name: 'email',
rules: [
{ test: (value: string) => !value.trim(), message: 'Email address is required' },
{ test: (value: string) => !/\S+@\S+\.\S+/.test(value), message: 'Email address is invalid' }
]
}
];
import React from 'react';
import { useFormBlurValidation } from '@sksuri/form-blur-validation-hook';
const MyComponent: React.FC = () => {
// Initial form state
const initialFormState = {
email: '', //property name should match with name attribute of input fields.
};
// Form validation using custom hook
const {
formData,
errors,
isDisabled,
handleInputChange,
handleBlur,
isFormValid
} = useFormBlurValidation(initialFormState, validationRules);
// Handle form submission
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (isFormValid) {
// Form is valid, submit the data
console.log('Form submitted:', formData);
} else {
// Form is invalid
console.log('Form has errors');
}
};
return (
<div>
<h2>My Component</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Email</label>
<input
type="text"
name="email"
value={formData.email}
onChange={handleInputChange}
onBlur={handleBlur}
/>
{errors.email && <span>{errors.email}</span>}
</div>
<button type="submit" disabled={isDisabled}>Submit</button>
</form>
</div>
);
};
export default MyComponent;
In above example:
- We import the
useFormBlurValidation
hook from the@sksuri/form-blur-validation-hook
package. - Inside the component, we define the initial form state and validation rules.
- We use the
useFormBlurValidation
hook to handle form validation, which provides form data, error messages,isFormValid
boolean value to determin whether form is valid or not and functions for input change, blur. - We use the provided functions
handleInputChange
,handleBlur
to handle form interactions and submission. - Each input field is associated with its corresponding value in the
formData
object, error message from theerrors
object, and change/blur event handlers. - The submit button is disabled (
isDisabled
) if there are any validation errors in the form.