DateTime Validation Setting How do you set date cannot be empty

Topics: General discussion, Validation Application Block
Feb 26, 2009 at 2:15 PM
Hi,

I need to set up the following

I have class MyClass with StartDate and EndDate


StartDate can be empty
EndDate must Be greater or equal then start date (Property Comparison)
EndDate Cannot be empty  (how do you set this one?)

can somebody help with the above basic requirements?  I am using the config file

thanks for any suggestions
Feb 27, 2009 at 2:43 AM
Edited Feb 27, 2009 at 2:44 AM
Hi,

Is your DateTime Nullable? If it is, you can use the not null validator and use the And Composite Validator to join the not null and the property comparison. 

Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com
Feb 27, 2009 at 4:51 AM
hi
thanks for your reply.
No my datetime is not nullable and changing it would mean changing in so many places that can't do.

My question is the same How do you set up any example even using attribute and I will convert it will be really appreciated.

StartDate can be empty
EndDate must Be greater or equal then start date
EndDate Cannot be empty  (how do you set this one?)

thanks again

Feb 27, 2009 at 2:31 PM
Edited Feb 27, 2009 at 2:35 PM
Hi,

First thing, how can I set a DateTime type to be empty? Assuming you have a UI which the user inputs the date(in a textbox), if the textbox is left empty, I assign the enddate to new DateTime() which will have a value of 1/1/0001. Now we have a empty date, to validate that and tell the user that date cannot be empty. Here is a sample.

I created a class with a start date and end date, with a dummy property which returns a empty date, (new DateTime())

    public class Payroll

    {

        public DateTime StartDate { get;set; }

        public DateTime EndDate { get; set; }

 

        public Payroll(DateTime start, DateTime end)

        {

            this.StartDate = start;

            this.EndDate = end;

        }

 

        public DateTime EmptyDate

        {

            get

            {

                return new DateTime();

            }

        }

    }

 

 

 

 

In my config:

1. Add a And Composite Validator to the EndDate property.
2. Add a Property comparison validator to the And Composite Validator
3. Configure the Property comparison validator to be "NotEqual" to the EmptyDate Property.
4. Add another Property comparison validator to the And Composite Validator
5. Configure that Property comparison validator to be "GreaterThanEqual" to the StartDate Property.

As far as I've tested it. It works fine. Please give feedback if I missed out something.

Hope this helps.

Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

 

 

Feb 28, 2009 at 9:13 AM
First of all 
thanks for your reply.Really appreaciated. Unfortunately Dates have always been tricky
Now what i have done to simplify the lot i have made both Start Date and EndDate nullable.
However what I have noticed is that if I set the StartDate=null; the all thing does not work it works if i set to new DateTime

The way I have set up the config is
ExpiryDate
      And Composite Validator
            PropertyComparison NotEqual
            PropertyComparison GreaterThanEqual
            NotNull Validator
     

the class is this

public

 

class Payroll
{
    public Payroll(Nullable<DateTime> startDate, Nullable<DateTime> expiryDate)
    {
            this.StartDate = startDate;
            this.ExpiryDate = expiryDate;}

 

 

 

            public Nullable<DateTime> StartDate { get; set; }
            public Nullable<DateTime> ExpiryDate { get; set; }
      }

 

}

 

 

private ValidationResults GetValidationResults()
{
    DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
     dtfi.YearMonthPattern =
"MMYY";//this a compulsory pattern for what we are doing regardless of culture

 

 

 

if (txtStartDate.EditValue == null)
       payRoll.StartDate =
new DateTime();  //SETTING TO NULL THEN THE CONFIG WONT PICK IT UP
  else
{
     if (IsDate(txtStartDate.Text))
         payRoll.StartDate =
DateTime.Parse(txtStartDate.Text.ToString(dtfi));
}
if (txtExpiryDate.EditValue == null)
     payRoll.ExpiryDate =
null;
else
{
if (IsDate(txtExpiryDate.Text))
    payRoll.ExpiryDate =
DateTime.Parse(txtExpiryDate.Text.ToString(dtfi) );
}

 

 

 

ValidationResults results = Validation.Validate(payRoll,"PayrollRule");

 

 

return results;

 

}

 

the config is this

<type defaultRuleset="PayrollRule" assemblyName="MyCompany.Business.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
      name="MyCompany.Business.Entities.Payroll">
      <ruleset name="PayrollRule">
        <properties>
          <property name="ExpiryDate">
            <validator type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.AndCompositeValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
              name="And Composite Validator">
              <validator negated="false" messageTemplate="Expiry Date Cannot be empty"
                messageTemplateResourceName="" messageTemplateResourceType=""
                tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="ExpiryDateCannotBeNull" />
              <validator operator="NotEqual" propertyToCompare="StartDate"
                negated="false" messageTemplate="Expiry Date Cannot Be Equal To StartDate"
                messageTemplateResourceName="" messageTemplateResourceType=""
                tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.PropertyComparisonValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="ExpiryDateCannotBeEqualToStartDate" />
              <validator operator="GreaterThanEqual" propertyToCompare="StartDate"
                negated="false" messageTemplate="Expiry Date must be greater or equal start Date"
                messageTemplateResourceName="" messageTemplateResourceType=""
                tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.PropertyComparisonValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="ExpiryDateMustBeGreaterThanEqual" />
            </validator>
          </property>
          <property name="StartDate" />
        </properties>
      </ruleset>
    </type>

 




In  a nutshell why by settings the nullable date to null the above settings dont work, I want to avoid to be doing things like if  date=0001 etcc set to null before saving to db.

thanks a lot

 

Feb 28, 2009 at 3:22 PM

Hi,

I've tried you provided code snippet and config. and it seems that its working fine. even if I set the StartDate to null, on what specific condition that you are getting a unexpected behavior? Also if you can send your solution it would be great so we can have a closer look.

Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Feb 28, 2009 at 4:38 PM

Hi Brix, 

    StartDate can be empty
    EndDate must Be greater or equal then start date (Property Comparison)
    EndDate Cannot be empty  (how do you set this one?)

I'm new to EnterpriseLibrary 4.1 (like starting today :) and since the days of CAB I've learned the best way to learn new P&P projects is to start with the Unit Test; as with Unity I was not disappointed - there are a wealth of Unit Test for all of the EntLib features.   The other thing I do is review message board content to see what the high volume issues are (so when I encounter them I know how to address them).

When I saw the Unit Test that follows I thought of your question because the validator is being sent a null date string which is later being compared to {1/1/0001 12:00:00 AM} and passing.  Suggesting that validation could be simplified to following:

    StartDate can be empty  => where StartDate can be 1/1/0001
    EndDate must Be greater or equal then start date (Property Comparison)   => greater than 1/1/001 if null 
    EndDate Cannot be empty  (how do you set this one?) =>  not allowed to be 1/1/0001

 
Perhaps the following, or one of the other many validation test (search project for "DateTime"), might help you?

Bill
<installation folder>\Blocks\Validation\Tests\Validation.Tests\Validation.Tests.VSTS   Project
     -> \Blocks\Validation\Tests\Validation.Tests\Validators\DateTimeRangeValidatorAttributeFixture.cs

        [TestMethod]
        public void ConstructorCallWithNullStringDateUsesDefaultDateTimeValue()
        {
            ValidatorAttribute attribute = new DateTimeRangeValidatorAttribute((string)null);

            Validator validator = ((IValidatorDescriptor)attribute).CreateValidator(null, null, null);
            RangeValidator<DateTime> rangeValidator = validator as RangeValidator<DateTime>;

            Assert.AreEqual(default(DateTime), rangeValidator.UpperBound);
        }


Breakpoint above reveals that rangeValidator.UpperBound = {1/1/0001 12:00:00: AM}