0

I am learning Java Servlets and I am working on a simple homework assignment. I have an html page containing a form, that is submitted to a servlet, does some processing, and uses a printwriter to render an html page with results.

Now, I want to add Javascript, which I am familiar with. Is there a way that I can write a Javascript function to validate data in the form, and if the data is valid, then call the servlet, otherwise, don't call the servlet?

0

1 Answer 1

7

What you need is just form validation with Javascript.

First you need to include a call to a Javascript validation function into the onsubmit attribute of your form. Something like:

<form name="myForm" action="YourServlet" onsubmit="return validateForm()">
    ...
</form>

Then, if you're really familiar with Javascript, your validation function should be easy to create... Basically it's something like:

function validateForm() {
  //Check form fields:
  //If they're are correct return true,
  //otherwise return false...
}

If the validation function validateForm() returns false, the form won't never be submitted, that's to say, the servlet won't be called...

Note: usually you will have a validation function that actually calls other functions to check different parameters, as you can see at the end of this tutorial.

Sign up to request clarification or add additional context in comments.

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.