0

I ave a question, I've builded an form in HTML. It has an input field called postal code. Now I want the form to check if the postal code entered in that field is in range before submitting.

So if the postcalcode isn't in range it won't submit and notices the user the postal code isn't in range. What's the best way to do that?

This is my input field code

<div class="field-element ">
 <input type="text" name="MERGE4" id="MERGE4" placeholder="Postcode *" class="shortnice form-input required"/>
</div>

1 Answers1

1

You will do like this:

<html>
    <head>
        <title>Postal code</title>
    </head>

    <body>
        <form>          
            <input id="the_right_way" class="zipcode" type="text" value = "" pattern="^\d{5}(?:[-\s]\d{4})?$">
            <input type="submit" value="Submit"/>
        </form>
    </body>

</html>

If user enter invalid postal code, when user press Submit button, browser will notice error.

Learn more: https://stackoverflow.com/a/2577239/3728901

Community
  • 1
  • 1
Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • Can U make an better example for me? I'm only wanting the following postal codes to be accepted: 1011, 1012, 1013, 1015, 1016, 1017, 1018, 1019, 1021, 1022, 1031, 1032, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1091, 1092, 1092, 1093 – Matthijs Otterloo Mar 21 '15 at 20:18
  • @MatthijsOtterloo You will use `pattern="^\10[0-9]{2}$"`, for interactive example: http://regexr.com/3alb0 – Vy Do Mar 22 '15 at 01:29
  • Thnx! How can I make my form show an error if it won't match? – Matthijs Otterloo Mar 22 '15 at 10:40
  • When user enter an invalid value, for random example `ag3dd34`, then press `Submit` button, **browser will warn the error** for user (You don't need do anymore). – Vy Do Mar 22 '15 at 12:58
  • Allright! I tested it, but still have a problem. I keep getting the message that my pattern is invalid..... – Matthijs Otterloo Mar 23 '15 at 14:11