Inline validation
About HTML5 validations
HTML5 Validation is a feature provided by HTML5, which allows the client-side form validation. The validation is performed by using the required attributes, pattern attributes, and other form-related attributes, such as max, min, step, etc. The validation is performed automatically when a user submits the form, without requiring any JavaScript code. The browser displays error messages when invalid data is entered, indicating the user what is wrong and what needs to be corrected. HTML5 validation makes it easier for the developer to ensure that the form data is valid and reduces the need for server-side validation, saving time and resources.
Our proposal
Our proposal is to use this kind of validation with register
function, a brief explanation about. It allows you to define the properties for a specific field in the form, making it easier to manage and render the field on the screen. The function can accept either a string or an object as an argument. If a string is provided, it is assumed to be the name of the field. If an object is provided, it should contain all the necessary properties for the field, such as name, type, placeholder, etc. By using register, you can ensure that your fields are properly registered and their values are properly tracked in the form state.
When passing an object as argument, you can provide a property named validate
. The validate
property in the register function is used to specify the validation criteria for a particular field in the form. This argument can either be a yup or a zod schema validation. The validation criteria are defined as a set of rules that the field's value must meet in order to be considered valid. For example, a validation rule could be that the field's value must be a valid email address. When the register function is called, the value of the field will be passed through the validation rules specified in the validate argument. If the field's value meets all of the validation rules, then it will be considered a valid value. If the field's value does not meet all of the validation rules, then it will be considered an invalid value, and an error message will be displayed. The validate argument is an optional parameter in the register function, so if you do not need to specify validation criteria for a particular field, you can omit it.
Example
<input
{...register({
type: "email",
name: "email",
validate: yup.string().email().required(),
})}
/>
Observation: The validate property in the register function can accept validations in either Yup or Zod format. The user can choose whichever format they are more comfortable with or find more suitable for their use case.