开发者

Error Checking Input, Javascript

I am trying to check that what the user inputs begins with two letters, followed by either 6, 8 or 10 numbers. Checking string length should be ok but is there a neater way to check that the first two characters are letters and that the subsequent 6, 8 or 10 characters 开发者_Python百科are numbers than converting each character to unicode and then checking that way?


You can use regex:

^[a-zA-Z]{2}(?:\d{6}|\d{8}|\d{10})$

This will pass only if the first 2 are alphas and next 6 or 8 or 10 are numbers.

JS:

function isValid(txt) {
    return /^[a-zA-Z]{2}(?:\d{6}|\d{8}|\d{10})$/.test(txt);
}

alert(isValid("ab123456"));   // pass
alert(isValid("ab1234567"));  // fail, contains 7 digits
alert(isValid("abc123456"));  // fail, starts with 3 chars 
alert(isValid("ab12345678")); // pass

Here's complete JS example: http://jsfiddle.net/mrchief/sRLrW/


Why not use regular expressions? Javascript has a decent regular expression support.


Going off the top of my head:

var str = 'abc1234567890';

if (/^[a-z]{2}[0-9]{6}(([0-9]{2}){0,2}$/.test(str)) {
   ...

}

Doing a [0-9]{6,10} wouldn't do, as that'd allow 7 or 9 digits, not just 6/8/10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜