简体   繁体   中英

Regular expression in jquery allow only one match

Okay, i've got the following problem. I used jquery to test a string with a regular expression. It works all fine, but....

In the Netherlands the zipcodes are 4 digits followed by 2 characters eg 1234AB. Now i use the following regex to find this: [0-9]{4}[AZ]{2} .

But when someone types 1234AB+948203848 for example. It also return true. And i don't want that! How can i make it return false when it's not 4 digits followed by 2 characters?

Thanks in advance.

JSBIN

Use anchors ^ and $ . So your regex would become:

/^\d{4}[A-Z]{2}$/

Just use anchors to indicate the beginning of the word ( ^ ) and the end of it ( $ ):

var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
                       ^                ^

As per your comments, you also want to capitalize the input. For this, you can use .toUpperCase() :

Test ---> JSBIN

$(document).ready(function(){
            $('[name=postcode]').keyup(function(){
            var str = $(this).val().toUpperCase();
            var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
            var res = patt.test(str);
                console.log(res);
            });
      });

Alternatively, you can use ^[0-9]{4}[a-zA-Z]{2}$ (note the [a-zA-Z] part) to check the four letters, no matter upper or lowercase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM