The return allows us to return the value true or false from our function to the browser, where true means “carry on and send the form to the server”, and false means “don’t send the form”. a form mailer).įinally, the form tag includes an onsubmit attribute to call our JavaScript validation function, validate_form(), when the “Send Details” button is pressed. In reality, you would of course send the data to your own CGI script, ASP page, etc. The form uses the post method to send the data off to a dummy CGI script on ’s server that thanks the user. This is so that we can reference the form by name from our JavaScript validation function. The form is given a name of "contact_form". The first part of the form is the form tag: You can see that the page consists of a JavaScript function called validate_form() that performs the form validation, followed by the form itself.
#Php form validation check if empty code
You might like to open the source code for this form in a separate window, so that you can refer to it throughout the tutorial. Try pressing the Send Details button without filling anything in the “Your Name” field. Our validation script will ensure that the user enters their name before the form is sent to the server. The form will include one text field called “Your Name”, and a submit button.
Let’s build a simple form with a validation script. You can then adapt this form to your own requirements. In this tutorial we’ll build a simple form with client-side JavaScript validation. Server-side form validation (usually performed by a CGI or ASP script) Server-side validation is more secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to do and quicker too (the browser doesn’t have to connect to the server to validate the form, so the user finds out instantly if they’ve missed out that required field!). There are two main methods for validating forms: server-side (using CGI scripts, ASP, etc), and client-side (usually done using JavaScript). For example, if your form has a box for the user to type their email address, you might want your form handler to check that they’ve filled in their address before you deal with the rest of the form. At the end, there’s a little exercise to keep you busy too!įorm validation is the process of checking that a form has been filled in correctly before it is processed. First we’ll explain why form validation is a useful thing, and then build up a simple example form, explaining things as we go along.
#Php form validation check if empty how to
This tutorial will show you how to create a JavaScript-enabled form that checks whether a user has filled in the form correctly before it’s sent to the server.