Home > other >  How can i make this JS code simpler help! Too much if statements
How can i make this JS code simpler help! Too much if statements

Time:12-02

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

CodePudding user response:

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'))
}

CodePudding user response:

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/

  • Related