An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
April 17, 2021 04:50 pm GMT
Original Link: https://dev.to/frantchessico/a-simple-and-easy-way-to-validate-form-fields-84n
A simple and easy way to validate form fields
Hello guys, in this post I will talk about the simplest and easiest way to validate form fields according to my point of view, please enjoy.
- First, let's create the validators.js file:
export const myValidators = { isEmpty (string) { if(string.trim() === '') { return true; } else { return false } }, isEmail(email) { const emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(email.match(emailRegExp)) { return true; } else { return false; } }, isLength(string, value) { if(string.length < value) { return true } else { return false } },}
- And finally, we will create the inputFields.js file:
import { myValidators } from './validators.js'// TODO: testing isEmail() methodconst isEmailMethod = () =>{ let errors = {}; const email = "[email protected]"; if (!myValidators.isEmail(email)) { errors.email = "Email Field must be valid!" } else { console.log(email) } if(Object.keys(errors).length > 0 ) { return console.log(errors) }}isEmailMethod()// TODO: testing isLength methodconst isLengthMethod = () =>{ let errors = {}; const password = "849350920@sofala"; if (myValidators.isLength(password, 9)) { errors.password = "your password is too short" } else { console.log(password) } if(Object.keys(errors).length > 0 ) { return console.log(errors) }}isLengthMethod()// TODO: testing isEmpty methodconst isEmptyMethod = () =>{ let errors = {}; const phone = "849350920"; if (myValidators.isEmpty(phone)) { errors.phone = "Phone Field must not be empty!" } else { console.log(phone) } if(Object.keys(errors).length > 0 ) { return console.log(errors) }}isEmptyMethod()
Thank you all
Original Link: https://dev.to/frantchessico/a-simple-and-easy-way-to-validate-form-fields-84n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To