开发者

Required Attribute for DateTime property

开发者 https://www.devze.com 2023-03-10 23:24 出处:网络
I\'ve wrote the below code for making appointed date as required field. But when remove the default date and try to submit, no error message is shown.

I've wrote the below code for making appointed date as required field. But when remove the default date and try to submit, no error message is shown.

[DisplayName("Appointed Date")]
[Required(ErrorMessage = "Appointed Date Is Required")]
public virtual DateTim开发者_JS百科e AppointedDate { get; set; }

Please let me know, if i need to do anything more.


Usually this has to do with non-nullable types failing in the model binder on parsing. Make the date nullable in the model and see if that solves your problem. Otherwise, write your own model binder and handle this better.

Edit: And by model I mean a view model for the view, to make the recommended change, if you want to stick with binding to your model in the view (which I am assuming is using EF), follow the write your own model binder suggestion

Edit 2: We did something like this to get a custom format to parse in a nullable datetime (which might be a good start for you to tweak for a non-nullable type):


public sealed class DateTimeBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }

        if (bindingContext == null)
        {
            throw new ArgumentNullException("bindingContext");
        }

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

        if (valueProviderResult == null)
        {
            return null;
        }

        var attemptedValue = valueProviderResult.AttemptedValue;

        return ParseDateTimeInfo(bindingContext, attemptedValue);
    }

    private static DateTime? ParseDateTimeInfo(ModelBindingContext bindingContext, string attemptedValue)
    {
        if (string.IsNullOrEmpty(attemptedValue))
        {
            return null;
        }

        if (!Regex.IsMatch(attemptedValue, @"^\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$", RegexOptions.IgnoreCase))
        {
            var displayName = bindingContext.ModelMetadata.DisplayName;
            var errorMessage = string.Format("{0} must be in the format DD-MMM-YYYY", displayName);
            bindingContext.ModelState.AddModelError(bindingContext.ModelMetadata.PropertyName, errorMessage);
            return null;
        }

        return DateTime.Parse(attemptedValue);
    }
}

Then register this with (by providing this class in your Dependency Injection container):


public class EventOrganizerProviders : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
        if (modelType == typeof(DateTime))
        {
            return new DateTimeBinder();
        }

                // Other types follow
        if (modelType == typeof(TimeSpan?))
        {
            return new TimeSpanBinder();
        }

        return null;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消