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() method
const isEmailMethod = () =>
{
let errors = {};
const email = "jaimeinoque20@gmail.com";
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 method
const 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 method
const 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()
Top comments (8)
What's wrong with
input type="email"
input length=
input required
?
In what context, JavaScript or HTML?
I don't understand, can you enlighten me?
I think that what you wrote in the article can be done without js, only through simple html. Take a look here: w3schools.com/html/html_form_attri...
Antonio, I understand you now. So, my idea in this article was not to bring something complex but if you pay close attention to my code you will realize that you have an idea where you can transform something complex according to your need. Well, it is possible to do form validation with HTML but very limited, the fields validated by HTML I edit them in the browser and change their behavior and this is not a very good web application or advisable. That is why web programming languages have emerged to eliminate the limitations of HTML. I don't know if I made you understand?
I am comfortable using JOI for form validation. It is a very effective library.
Try
return string.trim() === ''
Instead of if else, cleaner and more efficient