Validating forms, an easy way
Tags: javascript, web
Published: 2023-10-12 21:43:36

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.

```js
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](https://flems.io/#0=N4IgtglgJlA2CmIBcA2ADAOgOwEYA0IAZhAgM7IDaoAdgIZiJIgYAWALmLCAQMYD21NvEHIQAHhY4ABD1i1SpALwAdEGwhsEqgHzLqUqQFVSEagHMpABwBO8KBB60hpKWz5SAbrVjQn8KYR81mCkemIA9JK61GKBwVLQKuAAngBiQWCqUnQMSWBpGTp6BmL2HtEGJXIARvCwAUFJAK6k8NY58DoAooJt2fTwSBE1dRWVYqaWTWyuyZbwSUIAHmxZiaotbR1ZHc2t7QNZXrBNC6pZ4WMRZVc3xeMj9XF7bbQ8PN291lJv-E2C2SaYFq1iG4UeYxKk2ms3mi3gKzWUBe1l+OwGKLRICkl3u1wg5Tx0Jm6xAHiybDmZxApCa1Ugq2xx1OSQAynSGQBCC7RCJxMC8ljfXExO76KQAJXgliC6nMUiQYXCYrE1WFvLKCWRqlgfDMRXFSrF3BpdXgPHUAnITBwAA5UCAAL54GgDUQYABW5F4AiEIiYXm++XS8UUUigfB4QOEbAwZngbC6CAYggAQskAJJQAAUqmDhRAAEoANx6QNSXVmePfMMRqMp2PxxPJmPprO5kCV1SFvR6Qj-C0QAQVvVSbOOTaFqTAe6V6sYUzUNoACQAKgBZAAyUgA1GGAAalAnaAAkwAnrUd+PK+9L1Edveo-GopBmTYAat5fG5rC4w-2n0tfRs35AARJxaCnad7lsNgmnaMcZ3FSoElIYw2gAOQGT8fCgBUpHuFCDDAiC4wTDtNgOBhuykTkw3ObFCKIgAfZiRzMDssIYKQ2msIJuzwJiDAgUgAEF3j4f42Bw6B8KEyoSLYWgyLYCj9ixKc6IIkAsikAAyPTaJErCMJAjJwKUlS1Ned5uyneSDFY9iO3EiSpJ46w+Osbt7kdHt70ffNggwWgYC6DwY03ES-TaDtaXpDRVDwYiByAsd4CnJCDHgDAbHgCLBFA+BCFoJpYFUktZz1edFxXDdt3onSQDvAwEBmY5vyCP8pA-L8oCcLrsyXAB3KQQzACzaGzIKwELfzWoTKRXz8Zl4BcKQw2zAB5aoPXNWMAGt4GSUhsw6-qf1IQsMDAWhLDOjbtE8PqBt-CgPAAXTmlqK0WkSZKgcaNqWpShFW0gMFsKAmh4eBs3HeDbEEZLfinRQnqjTyY30wzfmSthrFOSrxWzf6+vGqcDOc1QAHV-EcfQZVfVwWH8flaM5bkizvPy7z0E1WgQQcrVEHAcCQAAmABOJ0XRADp3R4BQTWfP02FEao+CgZJoPFfhdVBKRhpYDR4B+6o3gOsw+P+KAkCkawzAt7McAlvBXbwCWAGY8EwKX-Ifag9EeXWDHsUhLDkZIkFMHwlwAWmqXUeAOn7hugNgWHtnA0FsMAftux3TETvg2DcMAkBwPOecfABiStQ5kPgDftqGeYFs1hZfUWJcrr2nQ+x0gA)

Here is another version, proxifying the formData.

```js
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 :

```js
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 !!!");
});
```