0

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.

0

3 Answers 3

4

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 .

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

1 Comment

Thanks, it works like a charm. Any idea how to add custom error msg?
2

You can use regular expression for this

[RegularExpression(@"^((?!Forbidden value).)*$", ErrorMessage = "Characters are not allowed.")]
public string Title { get; set; }

Comments

2

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

Comments

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.