I often see tons of 'if' when validating forms, sometimes it is a real mess.
You can see in the following example how we can validate a form without relying on 'if' statements.
Of course, it's a very simple case, but you can see the point.
For advanced validations, you can use predicate functions.
var myForm = document.getElementById("myForm");
var logger = document.getElementById("log")
function log (cause) {
logger.innerHTML += `<div>${cause}</div>`;
}
const getValidators = function (formData) {
return ({
isUserNameValid :
formData.get("username") != ""
|| log("Name error"),
isAccountValid :
formData.get("useracc") != "" && !isNaN(formData.get("useracc"))
|| log("Acccount error")
})
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
logger.innerHTML = "";
let validators = getValidators(new FormData(myForm))
let statevalues = (Object.keys(validators).map(v => validators[v]));
let isValidForm = statevalues.reduce((current, acc) => current && acc, true);
(isValidForm) && log("We can post the form !!!");
});
You can play with it here Forms
Here is another version, proxifying the formData.
var myForm = document.getElementById("myForm");
var logger = document.getElementById("log")
let userForm;
function log (cause) {
logger.innerHTML += `<div>${cause}</div>`;
}
const getValidators = function (userForm) {
return ({
isUserNameValid :
userForm.username != ""
|| log("Name error"),
isAccountValid :
userForm.useracc != "" && !isNaN(userForm.useracc)
|| log("Acccount error")
})
}
const handler = (formData) => {
return { get : (_, name) => formData.get(name) }
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
logger.innerHTML = "";
let formData = new FormData(myForm)
userForm = new Proxy({}, handler(formData))
let validators = getValidators(userForm)
let statevalues = (Object.keys(validators).map(v => validators[v]));
let isValidForm = statevalues.reduce((current, acc) => current && acc, true);
(isValidForm) && log("We can post the form !!!");
});
Note that we can simplify the code :
var myForm = document.getElementById("myForm");
var logger = document.getElementById("log")
function log (cause) {
logger.innerHTML += `<div>${cause}</div>`;
}
function isNumber (value) {
return !isNaN(value)
}
const getValidators = function (formData) {
return ({
isUserNameValid :
formData.get("username")
|| log("Name error"),
isAccountValid :
formData.get("useracc")
&& isNumber(formData.get("useracc"))
|| log("Acccount error")
})
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
logger.innerHTML = "";
let validators = getValidators(new FormData(myForm))
let statevalues = (Object.keys(validators).map(v => validators[v]));
let isValidForm = statevalues.reduce((current, acc) => current && acc, true);
(isValidForm) && log("We can post the form !!!");
});