Skip to content

Instantly share code, notes, and snippets.

@wellercs
Created July 27, 2012 23:16
Show Gist options
  • Save wellercs/3190985 to your computer and use it in GitHub Desktop.
Save wellercs/3190985 to your computer and use it in GitHub Desktop.
Validate client-side with dataset property
<html>
<head>
<title>Data Error Message Sandbox</title>
<script type="text/javascript">
function checkForm() {
var myformelement = document.getElementById('myformelement');
var usermessage = document.getElementById('usermessage');
if (myformelement.value == "") {
try {
alert(myformelement.dataset.errorMessage);
usermessage.innerHTML = "dataset";
}
catch(err) {
try {
alert(myformelement.getAttribute('data-error-message'));
usermessage.innerHTML = "getAttribute";
}
catch(err) {
alert("Invalid data");
usermessage.innerHTML = "basicAlert";
}
}
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<div id="usermessage"></div>
<form id="myform" name="myform" method="post" action="" onsubmit="return checkForm();">
<label for="myformelement">My Form Element</label>
<input type="text" id="myformelement" name="myformelement" value="" data-error-message="Invaid data in 'My Form Element'" />
<input type="submit" id="btnsubmit" name="btnsubmit" value="Submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment