1

I am trying to validate date value in dd/mm/yyyy format.I am getting error message even if I enter the date in correct format.

Here is my Code :

[Required(ErrorMessage = "Required Field.")]            
[RegularExpression(@"^((0[1-9])|([1-2][0-9])|3[0-1])\/((0[1-9])|(1[0-2]))\/[0-9]{4}$",ErrorMessage="Please enter in dd/mm/yyyy")]
[DataType(DataType.Date,ErrorMessage="Please enter date.")]
public DateTime BeginningDate { get; set; }
3
  • Which one of the error messages is showing up? Commented Dec 29, 2010 at 4:51
  • And what date are you entering? Commented Dec 29, 2010 at 4:56
  • 'The value '28/12/2010' is not valid for BeginningDate' Commented Dec 29, 2010 at 4:57

2 Answers 2

1

The error message you get comes from model binder, it has nothing in common with your attributes. I think, that if you want to check regular expression, you should use:

public string BeginningDate { get; set;}

and then convert it to DateTime by yourself, after model binding. You know that date has to be provided in specific format, but model binder is not that smart, uses web.config/server setting, and throws an error. Checking DateTime type by regular expression doesn't make sense, because it is already DateTime, not string. Model binding comes first and then validation.

Sign up to request clarification or add additional context in comments.

Comments

0
public class DateRegexAttribute : RegularExpressionAttribute, IClientValidatable
    {
    public DateRegexAttribute(string pattern)
        : base(pattern)
    {
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        try
        {
            date = (DateTime) value;
        }
        catch
        {
            return false;
        }

        var input = date.Date.ToShortDateString();

        Match match = Regex.Match(input, Pattern, RegexOptions.IgnoreCase);

        return match.Success;
    }


    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRegexRule(ErrorMessageString, Pattern);
        return new[] { rule };
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.