0

I know there's data annotation to validate data such as [Required], [Range()] and so on. Not to mention the unobtrusive validation that makes it easier in the client side. Many thanks to them.

But what about if you need to validate the value that depends on the entity's property value? I have this scenarion, say:

My models:

public class Schedule
{
  public int Id { get; set; }
  public DatetimeOffset StartDate { get; set; }
  public DatetimeOffset EndDate { get; set; }
}

Now in a form,

<input type="text" name="StartDate" />
<input type="text" name="EndDate" />

How would you validate that the EndDate should not be less than the StartDate? Is there a built-in attribute in data annotation for that? Or should make a custom one? It would be great if it would make use of the unobstrusive validation by microsoft.

Here's another scenario:

What if you would do validation that depends on the value that is saved in the db? Say,

public class Bag
{
  //constructor
  public int Capacity { get; set; }

  public virtual ICollection<Item> Items { get; set; }
}

public class Item
{
  //constructor
  public string Description { get; set; }

  public virtual ICollection<Bag> Bags { get; set; }
}

That if you would do validation on the Items being added to the Bag but if the user tries to input beyond the limit of the Bag's Capacity, should show the validation error.

Is this possible?

I'm currently using ASP.NET MVC 4. EF5 Code first approach.

Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67

1 Answers1

1

The first approach is to implement IValidatableObject:

public class Schedule : IValidatableObject
{
    public int Id { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (StartDate > EndDate)
        {
            yield return new ValidationResult("End date must be greater than start date.", new [] { "EndDate"});
        }
    }
}

It will be executed automatically during model binding on server side.

If you want to validate on client side, you also have options. One of them is remote validation. You can read about it here. To summarize: You have to create constroller and action, that takes validated values and returns if it is valid or not. It can take more than one value. For example ID and username if you want to check uniqueness.

Obviously sending values to server is not necessary in date comparison. You can implement your own validation attribute to handle comparison on client side. Someone tried to implement it here.

Community
  • 1
  • 1
LukLed
  • 31,452
  • 17
  • 82
  • 107