0

During some work i have tried to get a validation form working for my webpage. Out of all the alerts and if functions i've placed all but one is working. That is when i want it to validate the form's Postcode value to check it for all digits it doesn't work and will allow even 4 digits that are characters.

I've Tried many ways including :

for (var i=0;i<document.OrderForm.Postcode.value.length;i++){
temp=document.OrderForm.Postcode.value.substring(i,i+1)
if (digits.indexOf(temp)==-1){
alert("Invalid Phone Number !")
return false
   }
 }

and I've tried using the test functions such as

if(/^[0-9]+$/.test(document.OrderForm.Postcode.value)){
alert("Not a valid postcode")
return false
}

I've tried i think almost every possible combination of these and every variation i could think of. Any thoughts or suggestions would be greatly appreciated as i could source any help from older questions etc.

Cheers, Jesse

2 Answers2

0

You can try to use function like this:

function checkPostcode(postcode) {
    postcode = postcode.replace(/\s/g, "");
    var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
    return regex.test(postcode);
}

This is an example for UK postcode. You may modify it for your format.

WhiteAngel
  • 2,594
  • 2
  • 21
  • 35
0

One way to do it is by using the keycode.

HTML:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

JS:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

Demo

You can restrict the input length using the maxlength attribute in HTML.

Source

Another way to do this is to use HTML5 input type="number".

Community
  • 1
  • 1
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138