最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript regexp using val().match() method - Stack Overflow

programmeradmin1浏览0评论

I'm trying to validate a field named phone_number with this rules:

the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874

or can be 7 numbers 1234567

here i have my code:

        if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
            missing = true;

Why doesnt work :( when i put that into an online regexp checker shows good.

I'm trying to validate a field named phone_number with this rules:

the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874

or can be 7 numbers 1234567

here i have my code:

        if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
            missing = true;

Why doesnt work :( when i put that into an online regexp checker shows good.

Share Improve this question edited Dec 23, 2011 at 2:50 Matthias 16.2k5 gold badges43 silver badges86 bronze badges asked Dec 22, 2011 at 15:36 alexistkdalexistkd 8982 gold badges14 silver badges35 bronze badges 1
  • A few too many "val" ? val[] and val() – mplungjan Commented Dec 22, 2011 at 15:43
Add a comment  | 

4 Answers 4

Reset to default 6

You should be using test instead of match and here's the proper code:

.test(/^(3\d{9}|\d{7})$/)

Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).

Don't get confused by pipe. Must end each expression

if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
            missing = true;

http://jsfiddle.net/alfabravoteam/e6jKs/

I had similar problem and my solution was to write it like:

if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
    missing = true;
}

Try this, it's a little more strict.

.match(/^(3\d{9}|\d{7})$/)
发布评论

评论列表(0)

  1. 暂无评论