0

How would one create a data annotation that only allows string that either have letters and numbers or letters only.

Basically disallow number only strings.

Right now, I have a letter only validation and I can't find out how to also allow numbers IF there are letters present in the string.

[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "No numbers allowed in the sequence.")]

Thanks!

EDIT - Found a solution!

Basicall:

[0-9]*[A-z ]+[0-9]*

This regex works ALMOST perfectly...

It catches an error if the users enters a number-only string, but... If he adds a single space, he can get away with the string.

To prevent that little error, I simply catch any empty spaces in my POST method from my controller and add an error to the ModelState.

Thanks to @PhillipBetts for the Regex 101 link, which helped me solve this problem!

3 Answers 3

1

I think the simplest way is to change your regular expression to \D to indicate there is at least one non-digit.

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

3 Comments

That didn't do the trick sadly. It doesn't seem to be picking up any value with this.
@Raspberry weird - it will work fine in a Regex.Matches - you may want to play around with it a bit.
Well, what I meant is that, as soon as I enter a number, I get an error.
0

There are a bunch of resources out there to test and learn Regex. My favourite Regex 101.

It also has a library that you can search and find useful Regex. It also gives a handy explanation.

Anyway, hopefully this is what you're looking for :

^[\w ]+$

2 Comments

Problem is, a string like 1asdf or asdf1 should be valid. Can't use that.
Yeah, he only wants to reject strings which have only numbers. A string which has both characters and numbers is fine.
0

you should try the String contains method with your regex

https://msdn.microsoft.com/de-de/library/dy85x1sa(v=vs.110).aspx

1 Comment

Hmmm, that would imply that I would have to check the value in the controller, I am trying to find a way to get a working data annotation.

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.