ASP.NET Data Annotations Regular Expression: Don't allow following characters in Name: \, /, :, *, ;,

StackOverflow https://stackoverflow.com/questions/23487634

Question

As the title says, I'm looking for a regular expression that don't allow a user to submit the Name with characters : (colon), ; (semicolon), / (forward-slash), \ (backward-slash), * (asterisk) and . (dot)

[Required]
public string Name { get; set; }
Was it helpful?

Solution

I finally ended up with this solution thanks to great suggestions from people on this thread:

[Required]
[RegularExpression(@"^[^\\/:*;\.\)\(]+$", ErrorMessage = "The characters ':', '.' ';', '*', '/' and '\' are not allowed")]
public string Name { get; set; }

OTHER TIPS

For Not allowing some special characters -

^[^\\/:*;\.\)\(]+$

I was checking similar scenario recently but finally created a custom attribute to disallow certain characters. Knew this is old post but posting here so it might help someone.

public class RestrictInvalidCharacters : ValidationAttribute
{
    private string DisallowCharacter { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="RestrictInvalidCharacters"/> class.
    /// </summary>
    /// <param name="dCharacters">To get invalid characters.</param>
    public RestrictInvalidCharacters(string dCharacters)
    {
           this.DisallowCharacter = dCharacters;
    }

    /// <inheritdoc/>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // converting to generic collection to compare.
        var dChar = this.DisallowCharacter.ToCharArray().ToList();
        string propertyName = validationContext.DisplayName;
           
        // compare if the input string has any disallowed characters
        if (value.ToString().ToCharArray().ToList().Any(x => dChar.Contains(x)))
        {
            return new ValidationResult(this.ErrorMessage);
        }
        else
        {
            return ValidationResult.Success;
        }
    }
}

using the custom attribute in the property.

public class TestClass
{
    [RestrictInvalidCharacters(":;\/*.")]
    public string Name{ get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top