\$\begingroup\$
\$\endgroup\$
2
I have a simple class to ensure the date entered into a form is a valid date. Where can I improve it, have I missed anything?
public class ValidDate : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var dateToParse = value.ToString();
var parsedDate = new DateTime();
if (DateTime.TryParseExact(dateToParse, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out parsedDate))
return ValidationResult.Success;
return new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");
}
}
Thanks,
-
2\$\begingroup\$ I would consider to include the malformed input data into the error message. It can help a lot during investigation. \$\endgroup\$Peter Csala– Peter Csala2020年06月24日 13:41:19 +00:00Commented Jun 24, 2020 at 13:41
-
1\$\begingroup\$ @PeterCsala that's a good shout, thanks, I'll add that in. \$\endgroup\$MF1010– MF10102020年06月25日 07:33:15 +00:00Commented Jun 25, 2020 at 7:33
2 Answers 2
\$\begingroup\$
\$\endgroup\$
0
You could easily turn your method into a one-liner expression-bodied method with a few tricks:
- use the
_
discard variable instead of the explicitparsedDate
variable (also, it doesn't need initializing tonew DateTime()
). - use the conditional operator since you're returning one of two
ValidationResult
s. value.ToString()
can be passed directly intoTryParseExact
without the extra local variabledateToParse
.
Giving:
protected override ValidationResult IsValid(object value, ValidationContext validationContext) =>
DateTime.TryParseExact(value.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _)
? ValidationResult.Success
: new ValidationResult("Invalid date, please try again with a valid date in the format of DD/MM/YYYY.");
Couple more items:
- Recommend -- for ease of reading -- adding a
using System.Globalization;
to your namespace so you don't have to type that long prefix out twice. - As this is an attribute, add the suffix
Attribute
to your class name.
answered Jun 24, 2020 at 12:43
\$\begingroup\$
\$\endgroup\$
0
I think other answer had some great points, also I would use fluent validation instead so your model does not need to have dependencies on validation attributes.
answered Jun 24, 2020 at 15:06
lang-cs