-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidateform.php
More file actions
60 lines (52 loc) · 1.46 KB
/
validateform.php
File metadata and controls
60 lines (52 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
//defining null values to variables and empty sets
$name=$email=$age="";
$nameErr=$emailErr=$ageErr="";
if($_SERVER['REQUEST_METHOD']=="POST"){
if (empty($_POST['name'])){
$nameErr="name is required";
}
else{
$name=test_input($_POST['name']);
if(!preg_match("/^[a-zA-Z]*$/", $name)){
$nameErr="only letters and spaces allowed";
}
}
//email validation
if(empty($_POST['email'])){
$emailErr="email is required";
}
else{
$email=test_input($_POST['email']);
if (!filter_var($email,FILTER_VALIDATE_EMAIL)){
$emailErr="invalid email format";
}
}
//age validation
if(empty($_POST['age'])){
$ageErr="age is required";
}
else{
$age=test_input($_POST['age']);
if(!is_numeric($age)|| $age<1 || $age>120){
$ageErr="enter a valid age between 1 and 120";
}
}
}
//function to clean user input
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
name:<input type="text" name="name" value="<?php echo $name;?>">
<span style="color:red;">* <?php echo $nameErr;?></span><br><br>
email:<input type="text" name="email" value="<?php echo $email;?>">
<span style="color:red;">* <?php echo $emailErr;?></span><br><br>
age:<input type="number" name="age" value="<?php echo $age; ?>">
<span style="color:red">* <?php echo $ageErr; ?></span><br><br>
<input type="submit" value="submit">
</form>