0

I'm writing the validations in AngularJS. I've to allow exactly 6 digit positive number (6 digit whole number). I'm using following regex but it isn't working:

"pattern": /^\+?[0-9]+$/

it is accepting -15 also.

2 Answers 2

2

You didn't backslash the first plus sign. In regular expressions a plus sign means that the previous element should be matched one or more times. However, you just want a regular plus, so add a \ to it.

/^\+?([1-9][0-9]{5})$/

If you do more with regular expressions then RegExr.com is a great website where you can learn more and test them in real time.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't know how this could allow a dot there when only a plus and digits are specified in the regex. I didn't see you mentioning only exactly 6 digit numbers, check this one then: /^\+?([1-9][0-9]{5})$/
I'm using angularjs for the first time.
'society_zip': { 'title': 'Zip', 'type': "number", "pattern": /^\+?([1-9][0-9]{5})$/ this isn't working :-(
I don't know how it's checked inside your code, unfortunately. You probably want to extract the string that you need to check and execute a match function on it with this pattern. Clearly from RegExr you can see it's working as intended
0

The first matches any number of digits within your string. The second allows only 6 digits (and not less). So just take the better from both:

/^\d{1,6}$/

where \d is the same like [0-9].

For example:

    var data ='-15';
    var reg= /^\d{1,6}$/;
    alert(reg.test(data));
    /*
    1. '-15' will prompt false.
    2. '012345' will prompt true.
    3. '' will prompt false.
   */

Live example here

3 Comments

@Ritika: I update my code, Please check this should work.
I'm really surprised it is still not working. it is again allowing -15.1004 as input
So if this is your solution then please accept/vote. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.