Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
1.00/5 (5 votes)
See more:
regular expression to contain only numbers, format to value 8 digits with preceding zeros, and then validate
Posted
Updated 27-Nov-13 1:31am
v5
Comments
Richard MacCutchan 27-Nov-13 6:45am    
Is this a question or what? Have you tried to Google for regex and read the documentation for it?

Hi Reshmi,

Here is the regex for you ^[0+][0-9]{7}$

Note:Preceding with one or more 0's in the input.

Accepted input:
00045678
02345678
00000123

Invalid input:
12345678
423adad2
34@#$we4

You can test your value in here[^]

Hope this helps you a bit.

Regards,
RK
 
Share this answer
 
Comments
Reshmi Ranjith 27-Nov-13 7:31am    
thank u for the help. I have a slight modification in the question.Sorry for not being soo perfect in framing the question.
Can we add precedding zeros to the value to 8 digits and then validate for having only digits. Can this be acheived in regex?
♥…ЯҠ…♥ 27-Nov-13 7:34am    
Can you give some input that you want to validate?
Use this.

/^0*(1000|[1-9]\d{0,2})$/

C#
Explanation:

The 0* consumes any leading zeroes. After that, you're looking for either 1000 or a 1- to 3-digit number that doesn't start with zero. The [1-9] requires that at least one nonzero digit is present, and the \d{0,2} allows up to two digits after that (so numbers ending in zero are still allowed).
 
Share this answer
 
Comments
Reshmi Ranjith 27-Nov-13 7:31am    
thank u for the help. I have a slight modification in the question.Sorry for not being soo perfect in framing the question. Can we add precedding zeros to the value to 8 digits and then validate for having only digits. Can this be acheived in regex?
Regex is not the one and only solution to validate entries.
The length of a string is not really a "pattern" to be checked by Regex (similar to font and color and ...).

E.g. you could do
1) trim the text to take away leading an trailing white space characters (s = s.Trim();)
2) check the length of the remaining text (if (s.Length != INPUT_TEXT_LENGTH) ...)
3) if the length fits, check the text pattern by regex (if (!Regex.IsMatch(s, @"^\d+$")) ...)

Cheers
Andi
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900