Skip to content

Instantly share code, notes, and snippets.

@soldni
Created April 14, 2015 00:14
Show Gist options
  • Save soldni/74e2e96382b0f098319c to your computer and use it in GitHub Desktop.
Save soldni/74e2e96382b0f098319c to your computer and use it in GitHub Desktop.
Client-side check if data is a string
<!DOCTYPE html>
<html>
<head>
<title>Type check demo</title>
</head>
<body>
<form>
Insert only digit here<br>
<input id="digitsInput" type="text" name="digits" onblur="checkdigits()">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function isNumber(n) {
// returns True if n is a number, False otherwise
// source: http://stackoverflow.com/a/1830844/938048
return !isNaN(parseFloat(n)) && isFinite(n);
}
function checkdigits () {
// get element with digits
digitsInput = document.getElementById("digitsInput");
// check if inupt is invalid and if input has length greater than 0
if (!isNumber(digitsInput.value) && digitsInput.value.length > 0) {
// show a pop-up
alert('Please insert number only!');
// clear input
digitsInput.value = '';
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment