-3

Im a rookie in coding, an im figuring a way to shorten this code, it has too many if statements, if someone can help me out, i really apreciatted. I need to add a classList.remove to the same elements too after that

So this is the code:

const inputElementName = document.getElementById("name");
const inputElementMail = document.getElementById("email");

const validateInputName = () => inputElementName.value.trim().length > 0;
const validateInputMail = () => inputElementMail.value.trim().length > 0;

const handleInputName = () => {
    const inputNameIsValid = validateInputName();

    if (!inputNameIsValid) {
        return inputElementName.classList.add("error");
    } 
}

const handleInputMail = () => {
    const inputMailIsValid = validateInputMail();

    if (!inputMailIsValid) {
        return inputElementMail.classList.add("error");
    }
}
John99
  • 13
  • 1
  • 2
    2 if statements is too many ? Sure they both effectively do the same thing so there is some scope for improvement, but get it working first ! – John3136 Dec 02 '22 at 03:37
  • This will help. https://jsfiddle.net/codeandcloud/jr5aym6q/ – naveen Dec 02 '22 at 03:56
  • [the shortest way is to use automatic form validation == no more javascript needed.](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation) – Mister Jojo Dec 02 '22 at 04:03

2 Answers2

1

Do you mean to shorten them to make it DRY?

I see 2 functions are very similar, therefore you can reuse them a bit, especially the validation part and adding/removing error class. After that, you can reuse the function with any new input you have.

But remember not to overuse it, as long as it's readable to you and people and you can maintain it.

const isInputValid = element => element.value.trim().length > 0

const validateInputElement = inputElement => {
  if (!isInputValid(inputElement)) {
    inputElement.classList.add('error')
  } else {
    // not valid
    inputElement.classList.remove('error')
  }
}

const handleInputName = () => {
  validateInputElement(document.getElementById('name'))
}

const handleInputMail = () => {
  validateInputElement(document.getElementById('email'))
}
Đào Minh Hạt
  • 2,742
  • 16
  • 20
  • 1
    +1. Better if you could use [`toggle(token, force)`](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle) – naveen Dec 02 '22 at 03:59
1

Try this

const validateInput = (elm) => elm.value.trim().length > 0;
const handleInput = (elm) => {
    const isValid = validateInput(elm);
    elm.classList.toggle("error", !isValid);
    return isValid;
}

Fiddle: https://jsfiddle.net/codeandcloud/jr5aym6q/

naveen
  • 53,448
  • 46
  • 161
  • 251