So what I like to do is:
[NotLike(Value = "Forbidden value")]
public string Title { get; set; }
Is it possible? I've read the docs from Microsoft and could not find anything like this.
So what I like to do is:
[NotLike(Value = "Forbidden value")]
public string Title { get; set; }
Is it possible? I've read the docs from Microsoft and could not find anything like this.
You should be using ValidationAttribute
and inherit from it as follows:
public class NotLikeAttribute : ValidationAttribute
{
private string _NotLikeStr = "";
public NotLikeAttribute(string notLikeStr)
{
this._NotLikeStr = notLikeStr;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (!((string)value).Contains(_NotLikeStr))
{
var memberName = validationContext.MemberName;
var errorMsg = "Your Message";
return new ValidationResult(errorMsg);
}
}
return null;
}
}
and decorate your property as follows:
[NotLike("Forbidden value")]
public string Title { get; set; }
of course instead of using line below
if (!((string)value).Contains(_NotLikeStr))
you can split string to multiple words
or use Regular expression
or anything that meets your requirements .
I have two solution for you question:
1. Use [RegularExpression()]
You can use regular expression and create your own pattern for validation
For more information have a look at this link: Data annotation regular expression
2. Create new Custom Data annotation
You can create new custom data annotation (like what you did in question)
For more information have a look at this link: How to create Custom Data Annotation Validators
You can use regular expression for this
[RegularExpression(@"^((?!Forbidden value).)*$", ErrorMessage = "Characters are not allowed.")]
public string Title { get; set; }