jammydodger
jammydodger

Reputation: 17

How do I stop the form submitting with invalid fields in a form?

I've been using this Background colors on Luhn Algorithm - JavaScript to help build a similar webpage. However unlike the original poster I would like the code not to submit if there is any invalid inputs across any of the fields. I would still like the input fields to change colour (either green for valid or red for invalid).

I believe that I can fix both the name and email using a mixture of pattern (for the name - "[A-Za-z!#$%&'*+-/=?^_`{|}~]+") and using the input type of email for the email section. This is in addition to using 'required' for all the input fields. However it is with the card section that I am having the most trouble with. At the moment, I cannot figure out a way to not allow the form to submit if the card field is red. For example using the code in the original post, I can input '1', the input field will turn red, but I can still submit the form. I am assuming it is something to do with the section below but I am not sure what to change/add:

cardNumberInput.addEventListener("keyup", e => {
  const isCardValid = valid_credit_card(e.target.value);
  if (isCardValid) {
    cardNumberInput.style.backgroundColor = "green";
  } else {
    cardNumberInput.style.backgroundColor = "red";
  }
})

Any help would be greatly appreciated and I apologise for any missing details that you may need, it is my first question here.

Upvotes: 0

Views: 1760

Answers (1)

Kashan Ahmad
Kashan Ahmad

Reputation: 175

Make isCardValid global and add a submit event listener on your form like this

let isCardValid = false
const cardNumberInput = document.getElementById('your-input')
const cardForm = document.getElementById('your-form')

cardNumberInput.addEventListener("keyup", e => {
    isCardValid = valid_credit_card(e.target.value);
    if (isCardValid) {
        cardNumberInput.style.backgroundColor = "green";
    } else {
        cardNumberInput.style.backgroundColor = "red";
    }
})

cardForm.addEventListener('submit', e => {
    if(!isCardValid)
        e.preventDefault()
})

And the form won't be submitted until the isCardValid is true, if you want to submit the form manually instead of the default HTML submit behaviour, do this

yourForm.addEventListener(e => {
    // To prevent default submission always.
    e.preventDefault()

    if(!isCardValid) return

    // Do anything here...
})

Upvotes: 4

Related Questions