AJJ
AJJ

Reputation: 897

Specific number validation?

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

Answers (2)

Cleber Lopes
Cleber Lopes

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

flavian
flavian

Reputation: 28511

Should be really simple:

Live DEMO

  1. Create a list of your numbers
  2. Create an Object with every number as a key and whatever as a property.
  3. If they come from the server, send and parse them as JSON.// skip
  4. In JS, var validNumbers = JSON.parse(serverResponse); // skip
  5. Use an Object, not an Array. Array.prototype.indexOf is slower and needs polyfill.
  6. Object property access is O(1) and universally supported.
  7. Your object looks like this: var validNumbers = {"2747": "2747", etc..}
  8. Get the input from the user.
  9. if (typeof validNumbers[userInput] !== undefined) {//valid} else {//invalid}

Upvotes: 1

Related Questions