Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Custom validation attribute
Message
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
MVC
Titre:
Custom validation attribute
Versions des environnements
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Divers
Thread ID:
01552134
Message ID:
01552134
Vues:
61
Hi everybody,

Suppose I want to add a condition for my date to be greater than today's date. I can implement the logic in the class itself like this
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if ((EndDate==null) || (StartDate == null))
            {
                yield return new ValidationResult("StartDate or EndDate is null - something went terribly wrong!");
            }
            
            
            if (EndDate < StartDate)
            {
                yield return new ValidationResult("Class cannot end before it starts");
            }

            if (StartDate < DateTime.Now.Date)
            {
                yield return new ValidationResult("Start Date can not be in the past");
            }


            if (EndDate > StartDate.Value.AddMonths(1))
            {
                yield return new ValidationResult("You can not have a class longer than a month");
            }
        }
However, I see a few problems with this approach.

1. I'd like to have my validation rule a bit separate from the class itself - in a different file, may be? What is the general practice here, how such files are named and where do we put them?

2. I think it may be a better to create as custom data annotations attribute, say, FutureDatesOnly (I have similar propety in my VFP application).

Again, the question is - where do we create such custom attributes in the Objects project? Also, I assume most of such attributes are already developed by someone else - how can I know which attributes are already exist and how can I grab them?

Thanks in advance.

--------
Update. Reading this interesting blog now http://weblogs.asp.net/srkirkland/archive/2011/02/15/adding-client-validation-to-dataannotations-datatype-attribute.aspx although it looks too complex. I need something simpler.
If it's not broken, fix it until it is.


My Blog
Répondre
Fil
Voir

Click here to load this message in the networking platform