Search code examples
javascriptvalidationpostal-code

Validating the postcode so it can only start with LS


I want to be able to validate the text box so that it will only accept postcodes that start with LS.

This is specifically as this company is only delivering parcels in the leeds area, having a bit of nightmare with.

<!DOCTYPE html>
<html>
<body>

 <form name="myForm" action="stage2.php" onsubmit="return validateForm()"   method="post">
 Postcode: <input type="text" name="pcode">
 <input type="submit" value="Submit">
 </form>

 </body>
 </html>

This is my Javascript I'm Using

<script>
function validateForm() {
var x = document.forms["myForm"]["pcode"].value;
if (x == "LS" || x == "") {
    alert("Name must be filled out");
    return false;
    }
 }
</script>

Solution

  • <script>
        function validateForm() {
           var x = getElementsByName("pcode").value; 
           if (x == "LS" || x == "" || !(x.indexOf("LS")==0)) {
              alert("Name must be filled out");
              return false;
           }
        }
    </script>