Posts
208
Comments
1144
Trackbacks
51
EntLib Validation Application Block - Required String Validator

In a previous post I discussed validating strings with the VAB in the context of ASP.NET applications.  In summary, you must have a NotNullValidator and also a StringLengthValidator that prevents a string length of zero on the lower bound and prevents a string length above your upper bound (e.g., 50 characters).  That attribute might look like this:

   1:  [StringLengthValidator(1, 50, MessageTemplate="First Name must be 1-50 characters.")] 

But the problem is that the StringLengthValidator is really doing 2 jobs - one to check if the user entered a value and another to check the upper bound. Although including the NotNullValidator complete and correct, it doesn't do much in the context of asp.net applications which default to an empty string. 

So from a user perspective, it would be nice to have one message if the user leaves it blank and another message if they've exceed the upper bound (or didn't follow an appropriate Regex pattern, etc., etc.).  In other words, it would be nice to have a RequiredStringValidator so we could write our business object like this (notice we no longer have to care about the lower bound on the string length validator):

   1:  public class Person
   2:  {
   3:      [RequiredStringValidator(MessageTemplate = "First Name is required.")]
   4:      [StringLengthValidator(50, MessageTemplate = "First Name must be less than 50 characters.")]
   5:      public string FirstName { get; set; }
   6:  

Also, specifiying a MessageTemplate on the RequiredStringValidator is optional.

So creating your own custom validator to do this is actually quite easy.  The complete implementation follows:

   1:  public class RequiredStringValidatorAttribute : ValueValidatorAttribute
   2:  {
   3:      protected override Validator DoCreateValidator(Type targetType)
   4:      {
   5:          return new RequiredStringValidator(this.MessageTemplate, this.Negated);
   6:      }
   7:  }
   8:   
   9:  public class RequiredStringValidator : ValueValidator<string>
  10:  {
  11:      public RequiredStringValidator(string messageTemplate, bool negated) : base(messageTemplate, null, negated)
  12:      {
  13:      }
  14:      
  15:      protected override void DoValidate(string objectToValidate, object currentTarget, string key, ValidationResults validationResults)
  16:      {
  17:          if (string.IsNullOrEmpty(objectToValidate) != Negated)
  18:          {
  19:              LogValidationResult(validationResults, GetMessage(objectToValidate, key), currentTarget, key);
  20:          }
  21:      }
  22:   
  23:      protected override string DefaultNegatedMessageTemplate
  24:      {
  25:          get
  26:          {
  27:              return "Field cannot have a value.";
  28:          }
  29:      }
  30:   
  31:      protected override string DefaultNonNegatedMessageTemplate
  32:      {
  33:          get
  34:          {
  35:              return "Field is required.";
  36:          }
  37:      }
  38:  

I've supported Negations for completeness but I can't really think of a real-world example where you'd want to use it in this context. 

So overall, the RequiredStringValidator check for both null and empty string.  Thus, you don't have to feel like you're kludging the StringLengthValidator into doing two different jobs.

posted on Thursday, June 12, 2008 11:23 PM Print
Comments
Gravatar
# re: EntLib Validation Application Block - Required String Validator
PandaWood
8/19/2008 9:46 PM
My problem is the opposite, it seems that VAB4 is checking for null automatically.
I have a PhoneNumber as an Auto-property (C#3), and I set an UpperBound of 10. But if I don't set the property (ie it's null), it fails validation, and I'm wondering how to "stop it" doing this.

All I want is to alllow null or <= 10
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Sandro Mastronardi
8/29/2008 11:05 AM
I have the same problem, I can't find a way for now how to get around this.
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Swami
2/25/2009 11:24 AM
Use the following along with your phone number validator
[ValidatorComposition(CompositionType.Or)]
[NotNullValidator(Negated = true)]

This will allow null, but in case phonenumber is provided it will use the other validator.

Hope this helps.

Swami
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Gopinath Sundharam
2/4/2010 12:23 AM
Great trick. Thanks a lot.
Gravatar
# re: EntLib Validation Application Block - Required String Validator
sonali
6/21/2010 7:52 AM
When I use this Validator and try to created from the configuration file I get exception in protected override Validator DoCreateValidator(Type targetType)
{ in CustomValidator.cs
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Steve
6/21/2010 8:23 PM
@sonali - What is the exception that you get?
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Steven
8/29/2010 3:10 PM
When you use EntLib 5.0 you can combine VAB attributes with DataAnnotation attributes. This next decoration effectively solves the problem:

[Required]
[StringLengthValidator(50)]
public string FirstName { get; set; }

Cheers
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Murali
12/31/2010 3:23 AM
When i use Entlib5.0 against integer its throwing "not specified for .Int32" exception. Please guide me to resolve this issue.
[Required(ErrorMessage = "No of Employees must be between 1 and 50.")]
public int NoOfEmployees
{
get { return _noOfEmployees; }
set { _noOfEmployees = value; }
}
And used propertProxyvalidator to validate the control.
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Steve
1/1/2011 5:22 PM
@Murali - Is that [Required] validator one you wrote yourself? That's not part of the VAB. If so, I'd have to see your DoValidate() method - that's probably where your problem is.
Gravatar
# re: EntLib Validation Application Block - Required String Validator
Graeme
8/11/2011 4:56 PM
If you want to use the StringLengthValidator to prevent overruns but still make the field optional, use the [IgnoreNulls] attribute as well...

[IgnoreNulls]
[StringLengthValidator(10, MessageTemplate = ValidationTemplate.StringLength)]

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud