1

Hopefully that title made sense. Essentially I want to set up validation using Data Annotations in a class that will fail if one the fields (call it Field1 for example) equals a given string (i.e. "abc").

For example

public class myClass
{
    [Required]
    public string Filed1 {get;set;}    //*** I want validation to fail if this string equals "abc"
}

Hope that all makes sense. Any ideas?

Thanks

HuwD
  • 1,800
  • 4
  • 27
  • 58

1 Answers1

4

You can use RegularExpression attribute for this:

[RegularExpression("^(?!abc$).*$")]

The regex is a negative lookahead (basically checking that string does not start with abc followed by string end), and then allowing any other sequence.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • 3
    Be aware that `RegularExpressionAttribute` is case sensitive. This will still allow ABC, Abc, etc. – Jeremy Cook Mar 25 '14 at 15:55
  • 1
    Thanks, I thought RegularExpression might be the way to go but I'm useless at writing them. – HuwD Mar 25 '14 at 15:58
  • Extending `public class MyValidation : ValidationAttribute { ... }` is another way to go. A benefit of the regex attribute is it will also validate client side if you are sticking with Microsoft's guidance. – Jeremy Cook Mar 25 '14 at 16:11
  • An example of creating your own validation attribute and integrating with the client side validation can be found here: http://stackoverflow.com/questions/4218836/regularexpressionattribute-how-to-make-it-not-case-sensitive-for-client-side-v/14962296#14962296 – Jeremy Cook Mar 25 '14 at 16:12