useValidation

Validation

Every website with forms should have validations, but what are form validations? Go to any popular site with a registration form, and you will notice that they provide feedback when you don't enter your data in the format they are expecting. You'll get messages such as:

  • "This field is required" (You can't leave this field blank).
  • "Please enter your phone number in the format xxx-xxxx" (A specific data format is required for it to be considered valid).
  • "Please enter a valid email address" (the data you entered is not in the right format).
  • "Your password needs to be between 8 and 30 characters long and contain one uppercase letter, one symbol, and a number." (A very specific data format is required for your data).

But why is this so important?

Form validations are important to validate if the data is in the correct format and within the constraints set by the application. Usually, web applications have server-side and client-side validations.

Server-side validations are the last part of the validation, which means, even if the data is in the correct format it's possible that the data can't be persisted because some data can't be duplicated like email or username, this kind of validation is done in server-side. Client-side validation deal with incorrect data format, like a valid email, or a valid password, which means, that before the data is submitted the client-side validates if it is a valid data format.

Yup

Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

useValidation

useValidations is a custom hook that provides a easy way to validate forms with client-side validations, useValidations receives the form state, and a valid yup object with their data rules, and returns an object with errors state ans isValid state. useValidation will be called every time when values are changed.

PropertyDescription
errorsObject with all errors, this object is the same shape of object values.
isValidBoolean property

Usage

jsx
const validation = yup.object().shape({
name: yup.string().required('This field is required'),
email: yup
.string()
.email('This field must be a valid e-mail')
.required('This field is required'),
pets: yup.array(yup.string().required('This field is required')),
accept: yup.bool().oneOf([true], 'Field must be checked')
})
function Form(){
const { errors, isValid } = useValidation(values, validation)
return(
<form onSubmit={...}>
<input name="name" ... />
<span>{errors.name}</span>
<button type="submit" disabled={isValid}>Submit</button>
</form>
)
}