Home > Blockchain >  how to execute function after validation?
how to execute function after validation?

Time:07-11

I have a form and validation for it. The problem is that I don't know how to check if the fields are filled in correctly and then send. How can I submit after all fields are filled in correctly?

const addBanksFunc = () => {
  addBankButton.addEventListener("click", (event) => {
    event.preventDefault();
    checkInputs();
  });
};

const setError = (element, message) => {...};

const setSuccess = (element) => {...};

const checkInputs = () => {
  if (bankName.value === "") {
    setError(bankName, "Some text");
  } else {
    setSuccess(bankName);
  }

  if (interestRate.value === "") {
    setError(interestRate, "Some text");
  } else {
    setSuccess(interestRate);
  }

  if (maximumLoan.value === "") {
    setError(maximumLoan, "Some text");
  } else {
    setSuccess(maximumLoan);
  }

  if (minimumDownPayment.value === "") {
    setError(minimumDownPayment, "Some text");
  } else {
    setSuccess(minimumDownPayment);
  }

  if (loanTerm.value === "") {
    setError(loanTerm, "Some text");
  } else {
    setSuccess(loanTerm);
  }
};

CodePudding user response:

Just change your checkInputs signature, make it return true (form is valid) or false.

const checkInputs = () => {
  if (bankName.value === "") {
    setError(bankName, "Some text");
    return false;
  } else {
    setSuccess(bankName);
  }

  if (interestRate.value === "") {
    setError(interestRate, "Some text");
    return false;
  } else {
    setSuccess(interestRate);
  }
  ...

 return true;
}

and

const addBanksFunc = () => {
  addBankButton.addEventListener("click", (event) => {
    event.preventDefault();
    const isFormValid = checkInputs();
    if (isFormValid) {
        // submit the form here
    }
  });
};

Im actually not really sure about how to // submit the form with button onClick listener, probably it is better to use something like

orderForm.on('submit', function(event) {
    event.preventDefault();
    //some code here
    this.submit();
})

CodePudding user response:

Add an id or class for the form you want to submit. Lets say you have put an id="myForm" to the for you want to submit.

After all the checks, use the below code to submit the form through code.

document.getElementById("myForm").submit();

Note: put the submit button outside the form to avoid auto submission without the checks.

  • Related