LifeisG00d
LifeisG00d

Reputation: 27

How can I validate a string to only allow string or string with numbers but not numbers only?

I have textbox i want to give it expression for allowing string only or string with numbers but not to allow numbers only .. is this possible or not?

thanks guys your answers are really helpful but theres another issue tho can i prevent user also from writing these symbols : or ` or " or ) or [ or { or ~ or . or / etc.. i mean any symbols like those ones!

After @rinukkusu helped me with regex theres still one last thing though I dont want to allow the user to start the string with number and not in between also.. i want any number to be in the end of the string. I really appreciate your effort. Thanks!

heres the regex i used

(?!^\d+$)^[A-Za-z0-9]+$

Upvotes: 1

Views: 1210

Answers (3)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

This should solve your problem. Update: and only matches letters, underscores and of course numbers but not only numbers

<asp:RegularExpressionValidator
    ID="RegularExpressionValidator1"
    runat="server"
    ErrorMessage="Your error message"
    ControlToValidate="TextBox1"
    ValidationExpression="(?!^\d+$)^\w+$" >
</asp:RegularExpressionValidator>

If you want to specify which characters should be matched only, try this expression:

(?!^\d+$)^[A-Za-z0-9]+$

Upvotes: 0

Adriano Repetti
Adriano Repetti

Reputation: 67090

Yes it's possible, just ask for any sequence of numbers or digit but require that at least one letter is there:

/^(?![0-9]*$)[a-zA-Z0-9]+$/

It means: first group is any number of digits (considering whole string because it's tied to both begin and end), it's not allowed. Second group is any alpanumeric sequence long at least one character. Because first match will exclude numbers only then if this one is matche your text contains at least one character.

Upvotes: 1

Abbas
Abbas

Reputation: 14432

Use a regular expression. If the string is matched as a number, the input is invalid. Example:

string input = "2cc3d"; //valid

if(Regex.IsMatch(input, @"^\d+$"))
    Console.WriteLine("NOT VALID");
else
    Console.WriteLine("VALID");

If you don't want to do this in code, you should use the solution provided by "rinukkusu".

Upvotes: 0

Related Questions