Frage

I have a view model with a property which has RegularExpression DataAnnotation:

public class CreateProductViewModel
{
    [RegularExpression("[A-Za-z0-9]")]
    public string Name { get; set; }
}

The regular expression should validate only the alphanumeric characters.

However, trying to save "abc" value, makes the validation fail.

I've also tried to change the regular expression to "[^A-Za-z0-9]", but this one fails also.

What i am doing wrong?

War es hilfreich?

Lösung

Add * or + after the expression, because now it will show you that the string is valid only if it's one letter/number long. To make it works you have two options:

[RegularExpression("[A-Za-z0-9]+")]

or

[RegularExpression("[A-Za-z0-9]*")]

The first one will not allow empty string and the second will allow empty string.

Andere Tipps

Your original regular expression will only match a single alpha-numeric character. When you use it in a RegEx tester, it might appear that it works appropriately because it will match parts of the string. However, ASP.NET requires the Regular Expression to match the entire input string, effectively placing ^ and $ around your RegEx. If you want to match an input of more than one character you should add a quantifier to your RegEx, most likely * or +, like so:

[RegularExpression("[A-Za-z0-9]*")]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top