1

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??

3 Answers 3

1

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;" />
Sign up to request clarification or add additional context in comments.

1 Comment

It works on alert but When using the following code it again go to the next page. if(document.register.fname.value=="") { document.getElementById("error1").innerHTML="plz enter username"; return false; } @Thanos
1

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

Like this

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

Comments

1

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();
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.