Skip to content

Instantly share code, notes, and snippets.

@ledakis
Forked from marktyers/gist:d9cf82f8185ff9eff768
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ledakis/42ad93277aa36737c4e7 to your computer and use it in GitHub Desktop.
Save ledakis/42ad93277aa36737c4e7 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Validation</title>
<script>
window.onload = function() {
console.log('onLoad');
var form = document.forms.register;
form.onsubmit = function() {
console.log('onSubmit');
if (form.name.value.length == 0) {
console.log('empty field');
document.getElementById('nameError').innerHTML = 'Name field empty'
return false;
} else {
document.getElementById('nameError').innerHTML = ''
} // if
return true;
} // onSubmit
form.name.onblur = function() {
console.log('onBlur');
if (form.name.value.length == 0) {
console.log('empty field');
document.getElementById('nameError').innerHTML = 'Name field empty';
return false;
} else {
document.getElementById('nameError').innerHTML = '';
} // if
} // onBlur
form.phone.onkeyup = function() {
console.log('onKeyUp');
form.phone.value = form.phone.value.replace(' ', '');
if (form.phone.value.length == 0 || isNaN(form.phone.value)) {
console.log('failed validation');
document.getElementById('phoneError').innerHTML = 'Invalid phone number';
} else {
document.getElementById('phoneError').innerHTML = '';
}
} // onKeyUp
} // onLoad
</script>
</head>
<body style="margin:5em">
<form name="register" method="post" action="http://www.google.com/">
<p>Name:</br><input type="text" name="name"/><span id="nameError"></span></p>
<p>Phone:</br><input type="text" name="phone"/><span id="phoneError"></span></p>
<p><input type="submit"/></p>
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment