Validation in PHP
Validation in PHP is the process where we check if the input information in the various fields in any form such as text, checkbox or radio button, etc, submitted by the end-user in the form is correct or not using HTML code.
ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
There are 2 kinds of validation available in PHP:
- Client-Side Validation: This type of validation is done on the web browser of the client machine.
- Server-Side Validation: The data on submission is then sent to the server machine to perform validation checks there.
Rules to Validation in PHP
There are certain rules for validation of a form and they are as follows for the following fields:
- Name: It is a mandatory field whose data contains only whitespace and letters.
- Email: It is also a mandatory field that should contain a valid email address means it should be in the format of [email protected].
- Website: It is an optional field and should contain a valid URL if given
- Comment: It is an optional field and is a multi-line text input where we can give long sentences.
- Gender: It is a mandatory field and should select one gender out of the female, male and other.
Types of Validation in PHP
Now let us see how to validate different types of such fields.
1. Validation of text fields
There are a few text fields from the above-said attributes such as name, email, website, and comment. The HTML code for the same is as below:
Code:
<blockquote> <p>Name : <input name="name" type="text" /> <br /><br /> E-mail : <input name="email" type="text" /><br /><br /> Website: <input name="website" type="text" /><br /><br /> Comment: <textarea cols="40" name="comment" rows="5"></textarea></p> </blockquote>
Output:
Explanation to the above program: Here we can customize these attribute names however we want by using different header tags and also space tags. We have shown one of the paragraph format options for this one here.
2. Validation of radio buttons
Radio buttons are basically the ones having boolean value either true or false and they are represented by a circular box kind of a thing. If the box is circled it means true and vice versa. Let us check out the HTML code to implement the same for above said “Gender” attribute.
Code:
Gender:<br /><br /> <input type="radio" name="gender" value="female">Female<br /><br /> <input type="radio" name="gender" value="male">Male<br /><br /> <input type="radio" name="gender" value="other">Other
Output:
Explanation to the above program: By using this code we are displaying 3 options under the gender category as male, female and other. The user can circle on the required option by clicking on the circle and the option will be saved and validated.
3. Validation of form element
This method is used at the end after all the required details have been filled to submit the form. On using this HTML code the form data when submitted is sent with the “post” method. There are basically 2 attributes we need to specify while validating form element: action and method. We can convert certain HTML attributes to their respective entity names in order to prevent the form breaking when the user submits. “action” determines where the data of the form is sent on submission and “method” defines how the form’s data is submitted.
Code:
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Let us check an entire form of validation by combining all the different kinds of validation we learned above:
Code:
<!DOCTYPE HTML> <html> <head> <style> .Error {color: #FF0000;} </style> </head> <body> <?php // we are defining variables here and setting their default values to zero $nameError = $emailError = $genderError = $websiteError = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameError = "Name is mandatory"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailError = "Email is mandatory"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderError = "Gender is mandatory"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP Form Validation Example</h2> <p><span class="Error">* mandatory field</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <span class="Error">* <?php echo $nameError;?></span> <br><br> E-mail: <input type="text" name="email"> <span class="Error">* <?php echo $emailError;?></span> <br><br> Website: <input type="text" name="website"> <span class="Error"><?php echo $websiteError;?></span> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="other">Other <span class="Error">* <?php echo $genderError;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> <?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
Output:
Explanation to the above program: In the above example, we have combined all the different fields available such as text field, radio buttons and also email format types. The output will be displayed in the form of a box which will be according to the specification we give in the HTML code. Upon entering the mandatory values, the same are displayed under the text “The details entered are:”. Suppose any one of the mandatory values is not given then it will throw an error message besides that particular attribute saying that it is mandatory and needs to be filled.
Advantages of Validation in PHP
- By using client-side validation we can receive feedback faster without having to switch off from the server and download another HTML page.
- Validation on the client-side also helps in saving load on the server and increases performance.
Conclusion
We have seen in this tutorial how to do validation in PHP on the client-side and how much it is essential. It helps in saving time hence allowing for more bandwidth to point out the end-user their mistake in filling the given form. However, server-side validation is also important which is done using JavaScript, etc. Hence we can finally conclude by saying that both client and server-side validations are important since they complement each other in serving the end purpose.
The above is the detailed content of Validation in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
