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; }
}