How To Use Real-Time Validation?
Real-time validation is crucial for validating objects as they change dynamically, such as in user interfaces. This section outlines how to achieve real-time validation using the init()
method to track object changes and validate individual properties using the Validator library.
Steps to Implement Real-Time Validation
-
Define Data Types:
Define TypeScript types for the objects you want to validate. For example:
type Profile = { fullname: string; age: number; }; type User = { email: string; password: string; profile: Profile; };
-
Declare Validators:
Create validators for each property and nested object using the Validator library:
const profileValidator = v.validator<Profile>({ id: 'profileValidator', items: { fullname: v.string().required(), age: v.number().required().positive(), }, }); const userValidator = v.validator<User>({ id: 'userValidator', items: { email: v.string().required().email(), password: v.string().required().min(8), }, nested: { profile: profileValidator, }, });
-
Initialize Object State:
Use the
init()
method to initialize the validator with the current object state. This is essential for tracking changes and validating in real-time, especially useful in scenarios like form validations:const user = new User(); userValidator.init(() => user); // Initialize with a function to retrieve the current object state
-
Validate Single Property:
You can validate a single property using the validator's: read more here
validator.items.<property>.validate()
methodvalidator.nested.<nested-property>.items.<property>.validate()
method.
This allows you to validate specific fields as they are updated in the UI:
// Example to validate the 'email' property
const emailValidatorItem = userValidator.items.email;
emailValidatorItem.validate();
// Get validation status and error message
const isValid = emailValidatorItem.valid;
const errorMessage = emailValidatorItem.message;
// Update validation state if needed
if (!isValid) {
emailValidatorItem.error('Email is not valid!');
}
By following these steps, you can implement robust real-time validation for your application using the Validator library, ensuring data integrity and user experience consistency. Adjust validations and error handling according to your specific application requirements for seamless integration and functionality.