0

I want to validate a value from html form in JavaScript function, the format is a bit flexible.

i.e,

1 or 2 or 3 or 4 or 5 integer value followed by back slash(/) followed by 1 or 2 or 3 integers.

Example.

12345/123 is a valid value.

1234/12 is a valid value.

123/123 is a valid value.

1/1 is a valid value.

a/123 is NOT a valid value.

123/% in NOT a valid value.

2
  • 2
    What have you tried so far? regular-expressions.info is a good start to learn about regular expressions. Jan 19, 2013 at 10:57
  • regular expressions are something that i m not comfortable with it, Also i am short on deadline so can't afford time to create one, thats why i asked here. the link looks fantastic, i will definitely look into it :) Jan 19, 2013 at 11:24

2 Answers 2

0

You can try this regex: ^\d{1,5}\/\d{1,3}$

Example:

var re = /^\d{1,5}\/\d{1,3}$/;

console.log(re.test('12345/123')); // true
console.log(re.test('1234/12')); // true
console.log(re.test('123/1')); // true
console.log(re.test('12/123')); // true
console.log(re.test('1/123')); // true
console.log(re.test('a/123')); // false
console.log(re.test('123456/123'); // false

That said, you should start from the basics:

http://en.wikipedia.org/wiki/Regular_expression

http://www.regular-expressions.info/

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp

Here you can find many examples: http://regexlib.com/?AspxAutoDetectCookieSupport=1

2
  • 1
    Perhaps add the start and end characters to your regex, otherwise e.g.: console.log( /\d{1,5}\/\d{1,3}/.test('99912345/123999') ); // true, i.e. use /^\d{1,5}\/\d{1,3}$/
    – MikeM
    Jan 19, 2013 at 16:48
  • yeah, thanks @MikeM. In hurry I totally forgot about it :)
    – Ragnarokkr
    Jan 19, 2013 at 17:00
0

You know, consulting the documentation isn't too much to ask sometimes ...

\d{1,5}/\d{1,3}

There are also good sites out there to learn regular expressions, such as regular-expressions.info.

1
  • thank you for the reply and your time :)regular expressions is always the scary thing for me, thats why i asked to make sure i get the right result. Jan 19, 2013 at 11:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.