I realize the question already has an accepter answer, but I couldn’t help but notice you used the HTML5 doctype, which means you could use its new input types (such as email
, tel
and number
) and their validation attributes (such as min
, max
and pattern
).
That in combination with CSS’ :valid
and :invalid
pseudo-classes allows for real-time validation with 0 lines of javascript.
A simple quick incomplete example to illustrate above points:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<style>
body { font-family: sans-serif }
label { display: block }
label span {
display: inline-block;
width: 8em;
text-align: right;
margin-right: .25em;
}
input {
border-width: 2px;
border-radius: 1ex;
border-style: solid;
}
input:focus {
background-color: #41dcf4;
border-color: blue;
}
:valid { /* note that without a selector it applies also to whole form */
background-color: green;
border-color: green;
}
:invalid {
background-color: #f44242;
border-color: red;
}
</style>
</head>
<body>
<form>
<h1>Hello!</h1>
<p>If the box turns green, the information is valid!</p>
<label><span>first name</span>
<input
name="name"
required
pattern="[A-Z][a-z-]+"
>
</label>
<label><span>age</span>
<input
type="number"
name="age"
required
min="0"
max="100"
>
</label>
<label><span>email</span>
<input
type="email"
name="email"
required
pattern="[\w-.]+@[\w-]{1,62}(\.[\w-]{1,62})*"
>
</label>
<label><span>address</span>
<input
name="address"
required
>
</label>
<label><span>phone number</span>
<input
type="tel"
name="phone"
required
pattern="\d{3}-\d{3}-\d{4}"
>
</label>
<input type="submit">
</form>
</body>
</html>
- 960
- 7
- 10