Created
August 20, 2019 11:26
-
-
Save Ghanshyam-K-Dobariya/4a2710f589699ed1822e39a7b2bff5f5 to your computer and use it in GitHub Desktop.
Basic form validation using vanila js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> | |
<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