I have an "Update Profile" form with lots of input. The user can still update their profile even if they don't have all the inputs filled up. For example, if the user only wants to fill up the address field for now and decides to leave out all the other input fields, they are free to do so. The form will still submit.
However upon testing, when the "save" button is clicked, the form still submits and shows a success message even when NONE of the fields are filled up. I want to make a function that verifies first if at least one of the textboxes is filled up. If all the textboxes are empty, I want an alert to pop up, and also stop the form from submitting.
I tried searching from different pages but they're all mixed from questions from more than 6 years ago and I have trouble getting the syntax right. Can anyone provide me with a javascript syntax for these kinds of things so I can start from there? Thank you!
Use native HTML5 form/input elements. The browser will automatically test whether your input satisfies the type.
In this example we have a variety of fields (text, email, checkbox) all of which are required. The form can't be submitted until all the fields are complete. When the submit button is clicked we use a onsubmit listener attached to the form that calls a handler that uses preventDefault to stop the form from submitting, and then logs a message.
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit, false);
function handleSubmit(e) {
e.preventDefault();
console.log('Validated');
}
input { display: block; border: 1px solid black; }
input:invalid { border: 1px solid red; }
<form>
Name: <input name="name" type="text" pattern="[A-Za-z]+" required placeholder="Letters only" />
Email: <input name="email" type="email" required placeholder="Valid email"/>
Over 18: <input name="check" type="checkbox" required />
<button type="submit">Submit</button>
</form>