ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to validate Form with HTML and PHP Validatation

Updated on January 21, 2016

Basic Form Validation in HTML and PHP

Form validation is a important part of submitting form using PHP or other web development languages, it's mandatory to use form validation, otherwise hacker can play with your website or they can send spam etc, so it is important to learn form validation, today i am going to teach you basic form validation with HTML and PHP.

Now in HTML 5 there are many validation attributes like required, disabled, number, email, patterns, url many more, i added some html validation attributes for a simple validation, it's a just a little validation form a basic validation form that may help you for learning basic validation with HTML and PHP.

Let's start with HTML validation attributes, i used required attribute which is HTML 5 attribute, it's easy to set it, just write required on the last of your input types, after done, if user will not perform input and if user click on the submit button so a little box appear with the message of required.

I used required attribute in all input types, i also used on gender so if user not set gender then user will get a message box like this.

HTML Codes Explanation

I used form elements and attributes like action and method , it's important to set this for data sending or retrieving data on the page, action attribute is use for to do action, like if we set action="process.php" so it will perform the action process.php if we set nothing on action like this action="" so it will perform action to the current page as default, i am using method POST, for data sending or retrieving there are two ways POST And GET, for sending sensitive data always use POST method.

I created table i used tr table row and td table data, i used input types like text for user name, email for user email, number for mobile number, user can't enter text, only numbers are allowed, i used password for user password and radio for select gender then at the last i created submit button, it is very important to create submit button.

I tried to make my form validation page look cool and little attractive , so i tried to use CSS (Cascading Style Sheet), i hope you liked the design, let's don't talk about it, our focus should be on HTML, PHP.




HTML and CSS code

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
	<style type="text/css">
	
	body{
		background:#eee;
	}input[type=text], input[type=email], input[type=number], input[type=password]{
		width:400px; height:40px; padding:0px 5px; margin-bottom:5px; font-size:20px; font-family:verdana; font-weight:normal; color:#aaa;
	}
	tr td{
		font-size:20px; font-family:arial;
	}
	input[type=submit]{
		cursor:pointer;width:100%; height:60px; border:none; background:orange; color:#fff; font-size:20px; margin-top:10px;
	}
	input[type=submit]:hover{
	background:red;
	}
	.form-box{
		width:450px; padding:10px;  border:1px solid #ddd;margin:0 auto; margin-top:100px ;background:#fff; font-family:verdana;
	}
	</style>
</head>
<body>
	<div class="form-box">
		<center>
		<h1>Form Validation</h1>
		<form action="" method="post">
		<table>
			<tr><td><input type="text" name="name" id="" placeholder="Enter Full Name" required /></td></tr>
			<tr><td><input type="email" name="email" id="" placeholder="Enter Email Address" required /></td></tr>
			<tr><td><input type="number" name="mobile" id="" placeholder="Enter Mobile Number " required /></td></tr>
			<tr><td><input type="password" name="pass" id="" placeholder="Choose Password" required /></td></tr>
			<tr><td><input type="password" name="confirm_pass" id="" placeholder="Confirm Password" required /></td></tr>
			<tr><td>Gender : <input type="radio" name="gender" value="male" id="" required /> Male <input type="radio" name="gender" value="female" id="" required/> Female</td></tr>
			<tr><td><input type="submit" name="submit" value="Sign Up" /></td></tr>
		</table>
		</form>
		</center>
	</div>
</body>
</html>

PHP script

<?php
if(isset($_POST['submit']))
{
	$name = $_POST['name'];
	$email = $_POST['email'];
	$mobile = $_POST['mobile'];
	$pass = $_POST['pass'];
	$confirm_pass = $_POST['confirm_pass'];
	$gender = $_POST['gender'];
	

	$num_length = strlen((string)$mobile);
	if($num_length == 10) {
		if($pass == $confirm_pass)
		{
	
		echo '<script type="text/javascript">alert("Account Created Successfuly");</script>';	
			
		}
		else
		{	

		echo '<script type="text/javascript">alert("Password do not match!");</script>';
		exit();
		}
	
		}
	else{
		echo '<script type="text/javascript">alert("Mobile digits should be 10");</script>';
		exit();
	}
			
}


?>

PHP Code Explanation

I used isset() function to check the parameter in isset() function is set or not like i used if(isset($_POST['submit'])){} isset function will check if user clicked on submit or not if user clicked then if statements will execute.

I created some local variables like $name, $email etc, local variables are holding the value of user input.

I added little PHP validation like Mobile number can't be greater or lesser than 10 digits.

i added another validation to check if user password and confirm password is matching or not matching.

if you fill all the things correctly then you will receive the alert pop up from JavaScript.

Thanks, if you have any query or any problem just comment below.

Comments

    0 of 8192 characters used
    Post Comment

    • Abuzaransariweb profile image
      Author

      Abuzar Ansari 2 years ago from Lucknow

      Using Database.

      You can see my post about how to insert data into database using php.

    • profile image

      ramiz 2 years ago

      nice but how to save information which is inputted by the user

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)