Click here to Skip to main content
15,881,687 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi

I have a string variable as below.

string referenceNumber;
i want to validate referenceNumber as it should contain only alphabets,numbers and underscore(_).
ex:- ghk234_1

it should not allow any other except alphabets,numeric,and underscore(_).
Regards,
Nagaraju
Posted
Comments
Toli Cuturicu 24-Mar-11 16:25pm    
Are you sure you allow it to start with a digit?
Isn't it supposed to be a programming language identifier?

Look into regular expressions: System.Text.RegularExpressions.Regex.

String testString = "ghk234_1";
String regExpString = "[a-zA-Z0-9_]*";
Regex regex = new Regex(regExpString);
Match match = regex.Match(testString);
if(match.Success)
{
    //String was OK
}
else
{
    //String was not OK
}


Best Regards,
 
Share this answer
 
Comments
Nuri Ismail 24-Mar-11 12:04pm    
Good answer, my 5.

BTW: Using "\w" instead of "[a-zA-Z0-9_]" is shorter but maybe the longer version will be much clear for the OP. :)

Best Regards,
Nuri
Manfred Rudolf Bihy 25-Mar-11 5:45am    
Thanks Nuri!
Sergey Alexandrovich Kryukov 24-Mar-11 14:45pm    
Correct, a 5.
--SA
Manfred Rudolf Bihy 25-Mar-11 5:45am    
Thanks SA!
Use regular expressions. It's the most efficient way to analyze text information.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 24-Mar-11 14:46pm    
Short... why not? My 5.
--SA

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