Junaid afzal
Junaid afzal

Reputation: 25

JavaScript Validation form did not stop on error

I am making simple html form and doing validation using javascript.. But my form did not stop on error...

if(document.register.fname.value=="")
{

alert("plz enter username");
document.register.fname.focus();
alert("plz enter username");
return false;
}

Html Part is....

<input type="image" src="img/signup.PNG" alt="Sign Up" value="signup" onsubmit="return regis()" />

Even if I left the blank it goes on another page.... plz help me that what is the error??

Upvotes: 1

Views: 652

Answers (3)

c.P.u1
c.P.u1

Reputation: 17094

onsubmit only works on a form element, not an input element. Place your onsubmit inline handler in the form element.

A better option would be to use addEventListener as in:

document.register.addEventListener('submit', function(e) {
  if(document.register.fname.value === "")
  {
    alert("plz enter username");
    document.register.fname.focus();
    e.preventDefault();
  }
});

Upvotes: 1

Thanos
Thanos

Reputation: 3059

You should put the validation javascript on your form as appear below:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">

If you want to validate when the submit button is pressed try this:

<input type="submit" value="Submit this form" onclick="validateForm('myForm');return false;" />

Upvotes: 1

Joseph Myers
Joseph Myers

Reputation: 6552

You need to put the attribute onsubmit="return regis()" into the form tag of your form.

Like this

<form onsubmit="return regis()" ...

Upvotes: 1

Related Questions