This content originally appeared on DEV Community and was authored by Bello Shehu
Validation is a very important aspect of application development, in which user input data is tested against a predetermined format or value to ensure accuracy and quality of data entered into the application.
There are a bunch of tools used for validating user input both in the frontend and backend applications. Among such tools is yup; a very popular schema builder with value parsing and validation capabilities.
Below are examples of how to use yup to build user signup schema with validation in JavaScript.
1. Building basic user signup schema
This simple yup schema is for user signup containing user's email, password, and username. All fields are required:
const basic_signup_schema = yup.object({
email: yup.string().email().required("Email required"),
password: yup.string().required("Password required"),
username: yup.string().required("Username required"),
});
The .string
method validates email ID to string. Whereas, the .email
validates any email ID entered.
If this schema is used with a form library such as Formik, the individual form fields will be validated accordingly. Hence, the form will not be submitted if at least one of the fields is empty.
2. Adding more validation to signup schema
To make the user's password stronger and hence difficult for a hacker to guest, it must contain digits, upper and lower case, special characters and be at least 8 characters long.
const signup_schema = yup.object({
email: yup.string().email("Invalid email").required("Email required"),
password: yup
.string()
.min(8, "Must be 8 characters long")
.required("Password required")
.matches(/[a-z]+/, "Must contain lowercase character")
.matches(/[A-Z]+/, "Must contain uppercase character")
.matches(
/[_@$!%*#?&]+/,
"Must contain at least one special character among $ ! % * # ? & _ @ "
)
.matches(/\d+/, "Must contain digit"),
username: yup.string().required("Username required"),
});
Conclusion
Data validation is used to ensure security, and integrity of data stored in application's database. Hence, using a library such as yup is an effective and easier way you can ensure that the user enters correct data into your application.
For suggestions, correction and questions, kindly make a comment in the comment section.
Thanks for reading!
This content originally appeared on DEV Community and was authored by Bello Shehu
Bello Shehu | Sciencx (2024-06-22T11:36:12+00:00) Using yup to build schema with value parsing and validation.. Retrieved from https://www.scien.cx/2024/06/22/using-yup-to-build-schema-with-value-parsing-and-validation/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.