Form Validation in PHP
An HTML form contains various input fields such as text box, checkbox, radio buttons, submit button, and checklist, etc. These input fields need to be validated, which ensures that the user has entered information in all the required fields and also validates that the information provided by the user is valid and correct.
The code below checks that the field is not empty. If the user leaves the required field empty, it will show an error message. Put these lines of code to validate the required field.
The code below checks that the field will contain only alphabets and whitespace, for example - name. If the name field does not receive valid input from the user, then it will show an error message:
The below code validates that the field will only contain a numeric value. For example - Mobile no. If the Mobile no field does not receive numeric data from the user, the code will display an error message:
A valid email must contain @ and . symbols. PHP provides various methods to validate the email address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form. If the field does not contain a valid email address, then the code will display an error message:
Input Length Validation
The input length validation restricts the user to provide the value between the specified range, for Example - Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input:
The below code validates the URL of website provided by the user via HTML form. If the field does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".
Button Click Validate
The below code validates that the user click on submit button and send the form data to the server one of the following method - get or post.
Note: Remember that validation and verification both are different from each other.
Now we will apply all these validations to an HTML form to validate the fields. Thereby you can learn in detail how these codes will be used to validation form.
Create a registration form using HTML and perform server-side validation. Follow the below instructions as given:
Create and validate a Registration form
When the above code runs on a browser, the output will be like the screenshot below:
Fill the registration form and click on the Submit button. If all required information is provided correctly, the output will be displayed on the same page below the submit button. See the screenshot below:
Remember that we have not used a database to store the data for registered users.