Skip to content

Instantly share code, notes, and snippets.

@mmiinnovations
Created May 26, 2020 05:28
Show Gist options
  • Save mmiinnovations/b892ec08efca2f900d677d7dadcf7814 to your computer and use it in GitHub Desktop.
Save mmiinnovations/b892ec08efca2f900d677d7dadcf7814 to your computer and use it in GitHub Desktop.
JavaScript Form Validation
<form action="#" id="registration">
<h1>Register an Account</h1>
<p>
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password1">Password:</label>
<input type="password" id="password1" name="password1" />
</p>
<p>
<label for="password2">Confirm Password:</label>
<input type="password" id="password2" name="password2" />
</p>
<p>
<input type="radio" id="genderM" name="gender" value="male" />
<label for="genderM">Male</label>
</p>
<p>
<input type="radio" id="genderF" name="gender" value="female" />
<label for="genderF">Female</label>
</p>
<p>
<label for="continent">Your Continent</label>
<select name="continent" id="continent">
<option value="">Choose Your Continent</option>
<option value="africa">Africa</option>
<option value="northamerica">North America</option>
<option value="southamerica">South America</option>
<option value="antarctica">Antarctica</option>
<option value="asia">Asia</option>
<option value="australia">Australia</option>
<option value="europe">Europe</option>
</select>
</p>
<p>
<label for="desc">Describe yourself</label>
<textarea name="description" id="desc" cols="30" rows="10"></textarea>
</p>
<p>
<button type="submit" id="register">Register!</button>
</p>
</form>
<div id="errorMessages"></div>

JavaScript Form Validation

JavaScript Validation for XHTML:

Get a reference to the form with JavaScript. Validate each input field for a value. Compare passwords, but only if passwords have been given. (Stops comparison of empty passwords being considered the same). Check radio buttons have been selected. Display any error messages (that have been put inside an array during validation) as an unordered list beneath the form.

A Pen by Matt Trainer on CodePen.

License.

// Run function when DOM Content has loaded
document.addEventListener("DOMContentLoaded", init);
// Function to run when DOM Content has loaded
function init(event) {
// Get registration form and keep in global scope
regForm = document.forms["registration"];
// Listen for form submit
regForm["register"].onclick = validateForm;
}
// Function to validate form elements
function validateForm(event) {
// Array to contain all error messages
var errorMessages = Array();
// If username is empty
if (!regForm["username"].value) {
errorMessages.push("* Please enter Username");
}
// If password1 is empty
if (!regForm["password1"].value) {
errorMessages.push("* Please enter Password1");
}
// If password2 is empty
if (!regForm["password2"].value) {
errorMessages.push("* Please enter Password2");
}
// If both passwords have values
if (regForm["password1"].value && regForm["password2"].value) {
// If passwords don't match
if (regForm["password1"].value != regForm["password2"].value) {
errorMessages.push("* Passwords do not match");
}
}
// Find out if a gender has been selected
var isChecked = false;
for (var i = 0; i < regForm["gender"].length; i++) {
if (regForm["gender"][i].checked) {
isChecked = true; // Found a checked radio button!
break; // No need to continue the search
}
}
// If a gender selection was not found
if (!isChecked) {
errorMessages.push("* Please choose your gender");
}
// If selection has no value
if (!regForm["continent"].value) {
errorMessages.push("* Please select your location");
}
// If description is empty
if (!regForm["description"].value) {
errorMessages.push("* Please enter a description about you");
}
// Show error messages
displayErrors(errorMessages);
// If there are errors
if (errorMessages.length) {
// Stop the form from submitting
return false;
}
}
function displayErrors(errors) {
var errorBox = document.getElementById("errorMessages");
// If there aren't any errors
if (!errors.length) {
errorBox.innerHTML = "";
return false;
}
// Get reference to error box
var errorBox = document.getElementById("errorMessages");
// Prepare a container to hold the completed error message string
var messageString = "<ul>";
// Loop through each error to display
for (var i = 0; i < errors.length; i++) {
messageString += "<li>" + errors[i] + "</li>";
}
messageString += "</ul>";
errorBox.innerHTML = messageString;
}
/* Eric Meyer's Reset CSS v2.0 - http://cssreset.com */
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
margin: 0;
padding: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
body {
line-height: 1;
}
ol,
ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
}
body {
background: #3498db;
font-family: "Open Sans", sans-serif;
font-weight: 300;
}
#registration {
width: 480px;
background: #fff;
padding: 1em;
margin: 2em auto;
}
h1 {
font-size: 2em;
font-weight: 400;
text-align: center;
margin-bottom: 1em;
}
p {
padding: 0.5em 0;
}
p:after {
content: "";
display: block;
clear: both;
}
label {
display: inline-block;
width: 40%;
}
input[type="text"],
input[type="password"],
textarea,
select {
border: none;
padding: 0.5em;
background-color: #ecf0f1;
font: inherit;
float: right;
width: 50%;
}
textarea {
max-width: 50%;
min-width: 50%;
}
button {
border: none;
background: #3498db;
width: 100%;
padding: 1em 0;
font: inherit;
color: #ecf0f1;
font-weight: 400;
}
#errorMessages {
width: 480px;
margin: 2em auto;
background-color: #ecf0f1;
overflow: hidden;
}
#errorMessages li {
padding: 1em;
background-color: #e74c3c;
color: #ecf0f1;
font-weight: 400;
margin: 0 1em;
margin-bottom: 1em;
}
#errorMessages li:first-child {
margin-top: 1em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment