Skip to content

Instantly share code, notes, and snippets.

@Ghanshyam-K-Dobariya
Created August 20, 2019 11:26
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 Ghanshyam-K-Dobariya/4a2710f589699ed1822e39a7b2bff5f5 to your computer and use it in GitHub Desktop.
Save Ghanshyam-K-Dobariya/4a2710f589699ed1822e39a7b2bff5f5 to your computer and use it in GitHub Desktop.
Basic form validation using vanila js
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<script>
function isValidEmailId(emailId) {
var exp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
return exp.test(emailId)
}
function isValidPincodeNumber(pincode) {
return Number(pincode) === parseInt(pincode, 10) && pincode.length === 6
}
function getFormValidationMessage(isValidEmail, isValidPincode) {
var message = ''
if (isValidEmail == true && isValidPincode == true) {
message = 'valid'
} else {
message = 'Invalid'
if (isValidEmail == false) message = message + ' ' + 'email'
if (isValidPincode === false) message = message + ' ' + 'pincode'
}
return message
}
function validateForm() {
console.log('button clicked');
const email = document.getElementById("email").value
const pincode = document.getElementById("pincode").value
var isValidEmail = isValidEmailId(email)
var isValidPincode = isValidPincodeNumber(pincode)
var p = document.getElementById('message')
p.innerHTML = getFormValidationMessage(isValidEmail, isValidPincode)
return false;
}
</script>
</head>
<body>
<div id="app">
<form onsubmit="return validateForm()">
<p>
<label>
Email
<input type="text" id="email" />
</label>
</p>
<p>
<label>
Pincode
<input type="text" id="pincode" />
</label>
</p>
<input type="submit" value="Validate My Form" />
<input type="reset" value="Reset" />
<p id="message">....</p>
</form>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment