Validation before submitting

Hi, I tried a basic js code to validate username and it is not working. Please check where I am wrong.

Now when I click submit ,it should validate the form but it straightaway goes to the next page without validation how to recover from it.

Can anyone please suggest me how to write it.

Thanks in advance…

Hi @Murali207. Welcome to SItePoint. We can’t really help you unless you provide us with some code to look at. Just type three backticks (```) on a new line, then copy your code and type three more backticks on a new line to format the code for viewing.

Hi @Murali207 and welcome to the forum.

I have limited knowledge of JavaScript but there are many others gurus who can help.

Can you post the script you have tried which would help others find a solution.

Please post your script inside a starting and finishing line of three back ticks. The syntax highlighting will benefit others in solving your problem.

function validate() {
  var letter/^[a-zA-Z]+$/;
  if(letter.test(name)){
    return true;
  } else {
    alert ("must contain characters only");
    name.focus();
  }
}
<form name="myform" method="post" action="index.jsp" onsubmit="return validate(this);">
  <input type="text" name="name" required="required"/>
  <input type="submit" value="submit" onsubmit="validate()"/>
</form>

This is my code
Thanks in advance

Don’t forget to also have the server-side language validate the data as well. You might want to consider using ajax to have the server-side language check the value for each field as the input focus moves away from it.

You are not returning false when there is an error. to prevent the sumbit from happening

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.