Reputation: 897
Is it possible to validate a field to a specific set of numbers using javascript? Say for example in a postcode field you can only enter four numbers to be be accepted e.g. 2747,2750, 2753, 2760, 2777. Any other number will be returned as false. I have done a bit of searching around but i can't seem to find anything of use for this specific situation and i'm quite knew to javascript so any sort of help would be great.
Upvotes: 0
Views: 314
Reputation: 1
try this.
<html>
<head>
<script>
function validateForm() {
var x = document.getElementById("entry_834285895").value;
if ((x != 3242 )&&(x != 2342 )&&(x != 2343 )&&(x != 1111 )) {
document.getElementById("um").innerHTML = ('Invalid');
document.getElementById("um").style.color = 'Red';
}
else {
document.getElementById("um").innerHTML = ('Valid');
document.getElementById("um").style.color = 'Green';
}
}
</script>
</head>
<body>
<p>Valid numbers:<br> 3242<br>2342<br>2343<br>1111
<form name="myForm" action="" target="hiddenFrame"
onsubmit="return validateForm()" method="post" >
Name: <input id="entry_834285895" type="text" name="fname">
<input type="submit" value="Submit">
<div id="um"></div>
</form>
<iframe name="hiddenFrame" style="display:none;"></iframe>
</body>
</html>
Upvotes: 0
Reputation: 28511
Should be really simple:
Object
with every number as a key and whatever as a property.var validNumbers = JSON.parse(serverResponse);
// skipObject
, not an Array
. Array.prototype.indexOf
is slower and needs polyfill.var validNumbers = {"2747": "2747", etc..}
if (typeof validNumbers[userInput] !== undefined) {//valid} else {//invalid}
Upvotes: 1