-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFormValidationPractices.html
87 lines (68 loc) · 2.75 KB
/
FormValidationPractices.html
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS Form Validation</title>
</head>
<body>
<form name="regForm" onsubmit="return validateForm()">
<label>FirstName: </label>
<!-- <input type="text" id="fnameid" name="fname" oninput="validateFirstName()" required> -->
<input type="text" id="fnameid" name="fname" required><br>
<p id="pid"></p>
<label>LastName: </label>
<input type="text" id="lnameid" name="lname" required><br><br>
<p id="lid"></p>
<label>City: </label>
<input type="text" id="cityid" name="city" required><br>
<p id="cid"></p>
<input type="submit" value="Submit">
</form>
<script>
function validateForm(){
console.log("valid")
var firstName=document.forms["regForm"]["fname"].value
validateFirstName(firstName)
var lastName=document.forms["regForm"]["lname"].value
validateLastName(lastName)
var city=document.forms["regForm"]["city"].value
validateCity(city)
return false
}
function validateFirstName(firstName){
// var firstName=document.forms["regForm"]["fname"].value
var regex=/^[A-Za-z]+$/
if(regex.test(firstName)===true){
console.log("Valid")
document.getElementById("pid").innerHTML="Name is valid..."
document.getElementById("pid").style.color="green"
// document.write("Valid Name")
// alert("Valid name")
return false
}else{
alert("Invalid name")
return false
}
}
function validateLastName(lastName)
{
if(regex.test(lastName)===true){
document.getElementById("lid").innerHTML="Name is valid..."
document.getElementById("lid").style.color="green"
}else{
return false
}
}
function validateCity(city)
{
if(regex.test(city)===true){
document.getElementById("cid").innerHTML="Name is valid..."
document.getElementById("cid").style.color="green"
}else{
return false
}
}
</script>
</body>
</html>