8

I am using the [Required] data annotation on a string. This works just as intended, however it deems an input only consisting of white space to be invalid.

Is there any way to change this?

Jonathan
  • 13,947
  • 17
  • 94
  • 123

3 Answers3

12

There is an AllowEmptyStrings property on the RequiredAttribute. See if that helps.

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.requiredattribute.allowemptystrings

Jonathan
  • 13,947
  • 17
  • 94
  • 123
William
  • 1,375
  • 12
  • 27
5

According to MSDN you can use AllowEmptyStrings:

 [Required(AllowEmptyStrings = false)]
 public string CompanyName { get; set; }
Bizhan
  • 16,157
  • 9
  • 63
  • 101
Nicolars
  • 51
  • 1
  • 3
0

Although [Required(AllowEmptyStrings = true)] does allow whitespace, it also allows actual empty strings.

With [StringthLength(...)], you can permit whitespace but still forbid empty strings:

[StringLength(int.MaxValue, MinimumLength = 1)]
public string CompanyName { get; set; }
MarredCheese
  • 17,541
  • 8
  • 92
  • 91