0

I trying to validate string attribute in an object that created from data annotated model. This validation logic contains regular expression that checks whether the string is not empty or blank. Validation only fails when stringing with multiple spaces ("_________") it does not fail when attribute without space, that mean empty string("").

Annotated data model,

class Company
{
  [RegularExpression(@".*\S+.*$", ErrorMessage = "Website is empty")]
  [JsonProperty(PropertyName = "website")]
  public string Website { get; set; }
}

Calling for validation,

Company company = new Company(){
     Website = ""
};
var validationResults = new List<ValidationResult>();
var context = new ValidationContext(company, serviceProvider: null, items: null);
Validator.TryValidateObject(company, context, validationResults, true);

validationResults not capture the validation error.

Isuru Madusanka
  • 356
  • 3
  • 13
  • 2
    Why don't you use the [Required](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.2) attribute? - it does what I think you're after - _"A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters."_ – stuartd Sep 26 '18 at 11:47
  • 1
    .. although looking at your regex, it only seems to match strings containing non-space characters as well as spaces. Can you explain more clearly what you're trying to do? – stuartd Sep 26 '18 at 11:50
  • stuartd -> I need to invalidate model when an empty string and keep validate it when null value. – Isuru Madusanka Sep 26 '18 at 11:59
  • An 'empty string' and `null` are identical (as far as model binding is concerned) Its not clear what what you are wanting to validate –  Sep 26 '18 at 12:13
  • @Stephen Muecke https://stackoverflow.com/questions/6689876/string-empty-vs-null-which-one-do-you-use are not the same. – Isuru Madusanka Sep 26 '18 at 12:18
  • 2
    My validation is simple I want to have an empty string and blank string should have a validation error and NULL values have to be not. – Isuru Madusanka Sep 26 '18 at 12:20
  • Read my comment carefully - the model binder reads the value from the request - there is no such thing as `null` - its just text. So again, they are identical as far as model binding is concerned) –  Sep 26 '18 at 12:20

0 Answers0