Skip to content

Instantly share code, notes, and snippets.

@samthor
Created May 22, 2015 23:29
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 samthor/2c1e98ff5fcd0fe328bc to your computer and use it in GitHub Desktop.
Save samthor/2c1e98ff5fcd0fe328bc to your computer and use it in GitHub Desktop.
validation test
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,300italic,400,400italic" rel="stylesheet" type="text/css" />
<style type="text/css">
.formrow {
min-height: 32px;
line-height: 40px;
font-family: "Roboto", Sans-Serif;
font-weight: 300;
}
.formrow label[for] {
width: 120px;
display: inline-block;
text-align: right;
padding-right: 8px;
}
.formrow input {
border: 1px solid #666;
border-radius: 2px;
font: inherit;
line-height: 20px;
padding: 2px 6px;
}
.formrow input + div.message {
display: none;
color: red;
padding-left: 8px;
}
.notice .formrow input:invalid {
border-color: red;
}
.notice .formrow input:invalid + div.message {
display: inline-block;
}
</style>
<script>
window.addEventListener('load', function() {
var form = document.getElementById('testform');
form.addEventListener('invalid', function(ev) {
form.classList.add('notice');
});
form.addEventListener('submit', function(ev) {
console.info('submit event');
ev.preventDefault();
});
form.addEventListener('click', function(ev) {
var t = ev.target;
var valid = false;
if (t.localName == 'input' && t.type == 'submit') {
valid = true;
} else if (t.localName == 'button') {
valid = true;
}
if (valid && !form.checkValidity()) {
form.dispatchEvent(new Event('invalid'));
}
});
document.querySelector('input[type="submit"].direct').addEventListener('click', function(ev) {
ev.stopPropagation();
form.submit();
});
});
</script>
</head>
<body>
<form id="testform">
<div class="formrow">
<label for="form-username">Username</label>
<input type="text" id="form-username" name="username" placeholder="Username" required />
<div class="message">
Enter your username
</div>
</div>
<div class="formrow">
<label for="form-password">Password</label>
<input type="password" id="form-password" name="password" placeholder="Password" required minlength="6" maxlength="10" />
<div class="message">
Enter your password
</div>
</div>
<div class="formrow">
<label for="form-email">Email Address</label>
<input type="email" id="form-email" name="email" required />
<div class="message">
Enter a valid email address
</div>
</div>
<div class="formrow">
<label><input type="checkbox" required /> I've read the terms and conditions</label>
</div>
<input disabled type="submit" />
<input type="submit" />
<input class="direct" type="submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment