Skip to content

Instantly share code, notes, and snippets.

@nomanson
Last active December 15, 2015 00:19
Show Gist options
  • Save nomanson/5172395 to your computer and use it in GitHub Desktop.
Save nomanson/5172395 to your computer and use it in GitHub Desktop.
Form Validation I
.errorMessage {
color: red;
}
<form name="testForm">
<label>Write your full name:</label>
<input type="text" name="fullName" onchange="validateFullName()"
/> <span id="errFullName" class="errorMessage"></span>
<br />
<input type="button" value="submit" onclick="validateFullName()" />
</form>
/* this function grabs the content of the input element with ID 'fullName' and test if it's empty, only uses characters and has at least one space in it. The function is called by two events: both when any changes are made to the input field and when the button is clicked. */
function validateFullName()  {
/* we grab the content of the input field named 'fullName' in the form
named 'testForm' and store it in the variable 'field' */
var field = document.forms["testForm"]["fullName"].value;
// we create a new variable for our error messages and makes sure it is empty
var errMessage = "";
// we first test if the field is empty; the user forgot to write something.
if (field === "") {
errMessage = "No name was entered!";
/* next we use a 'regular expression' (regex) pattern to make sure only
letters and spaces are used (bad example since people would also have
foreign letters in their names in the real world). */
} else if (/[^a-zA-Z\b]/.test(field)) {
errMessage = "This is not a name!";
/* Finally we use regex to test that at least one space exists, to
ensure that more than a first or a last name is entered. */
} else if (!/\s/.test(field))  {
errMessage = "Enter your full name please!";
}
// we write our error message to the the span tag reserved for error messages.
document.getElementById("errFullName").innerHTML = errMessage;
}
name: Form validation I
description: Exampele of Javascript form validation including regex
authors:
- Jan Ingemansen
normalize_css: no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment