hi..

im trying to validate a registeration form using javascript..

i successfully validated all the textbox individually by using onblur event...

but

when i click submit button, without entering text, or without even touching the textbox, the Form gets Submitted..

hw can i stop this... plz tell me a solution...

Dani AI

Generated

Short summary tied to the thread: validated fields on onblur, so untouched fields never ran validation and the form submitted. was right that changing a <button> to type="button" prevents that default submit, but a more robust solution is to intercept the form's submit event and run the same validation there (this also covers Enter-key submits and cases where a user never blurs a field).

Quick examples (two safe approaches):

Use the classic inline onsubmit that returns false to stop submission:

<form id="regForm" onsubmit="return validateForm(this)">
  ...
</form>

<script>
function validateForm(form) {
  if (!form.username.value.trim()) {
    alert('Please enter a username');
    form.username.focus();
    return false;
  }
  // other checks...
  return true;
}
</script>

Prefer the unobtrusive / modern way with an event listener and preventDefault():

var form = document.getElementById('regForm');
form.addEventListener('submit', function(e) {
  if (!isFormValid()) {
    e.preventDefault();
    // show inline error messages, set focus, etc.
  }
});

function isFormValid() {
  // run the same checks that are used onblur
  return true; // or false
}

Practical notes and cautions:

  • Keep validation logic in one place and call it both from onblur handlers and from the submit handler to avoid duplication.
  • Changing a <button> to type="button" prevents clicks from submitting, but it also requires manually calling form.submit() after validation and does not replace handling Enter-key submits — so do not rely on that alone.
  • Consider HTML5 constraints (required, pattern) as progressive enhancement and always validate on the server as well.
  • For more on preventing submit and modern form validation patterns, see MDN: Form validation and Event.preventDefault().

Acknowledgement: gave the quick button-type fix and posted a related link; the submit-interception approach above gives a complete, reliable solution.

Recommended Answers

All 5 Replies

I cannot be sure(you have provided no code), but most probably the button that you are using to submit is of type submit, change the button to type button then and an onclick event and call your javascript function.

thanks Thirusha for the idea...

now i get logic..

pleasure, glad to help

thank u akoglu.e

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.