Skip to content

Instantly share code, notes, and snippets.

@przbadu
Created May 21, 2017 09:35
Show Gist options
  • Save przbadu/9d3570095ff78d2093533814cd1352b5 to your computer and use it in GitHub Desktop.
Save przbadu/9d3570095ff78d2093533814cd1352b5 to your computer and use it in GitHub Desktop.
Form validation to check, name should present, email should contain @ and . character and password should be atleast 8 character long
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form validation</title>
<script>
function validate() {
var name = document.getElementById('name').value;
var password = document.getElementById('password').value;
var email = document.getElementById('email').value;
var error = document.getElementById('error');
var emailRegx = /\S+@\S+\.\S+/;
if(name === "") {
error.innerHTML = 'Name should not be blank';
return false;
} else if(password.length < 8) {
error.innerHTML = 'Password should be atleast 8 character long';
return false;
} else if(!emailRegx.test(email)) {
error.innerHTML = 'Invalid email format';
return false;
}
error.innerHTML = '';
}
window.onload = function() {
document.getElementById('saveMe').onclick = function(e) {
e.preventDefault();
validate();
}
}
</script>
</head>
<body>
<form>
<p id="error" style="color: red;"></p>
<p><label for="name">Name</label>
<input type="text" id="name" placeholder="Name"></p>
<p><label for="password">Password</label>
<input type="password" id="password" placeholder="Password"></p>
<p><label for="email">Email</label>
<input type="text" id="email" placeholder="Email"></p>
<input type="submit" id="saveMe">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment