Charlie
Charlie

Reputation: 4895

Change ModelState In viewmodel(Add Custom Validation)

I am new to Web programming and i had to use Jquery datatime plugin. I was having a lot of problem in datatime conversions so i made a simple to me but weird and long logic to deal with it. Instead of creating One DateTime property. I made two, One is string and other is nullable Datetime in ViewModel

Note:All this code is written in ViewModel

  public DateTime? InitialStartDate
    {
        get
        {
            return istartDate;
        }
        set
        {
            istartDate = value;
        }
    }

    public string IStartDateString
    {
        get
        {
            if (istartDate == null)
            {
                return "";
            }
            else
            {
                return istartDate.Value.ToString("MM/dd/yyyy");
            }
        }
        set
        {
            if (string.IsNullOrEmpty(value))
            {
                istartDate = null;
            }
            else
            {
                DateTime TempDate=DateTime.Min;
                if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
                {
                  InitialStartDate=TempDate;
                }
                 else{
                  InitialStartDate=null;
                  ErrorMessage="Can not convert date";
              }
            }
        }
    }

Kindly tell me how to deal with it nicely.

Secondly

For instance this logic is good and then i want to add ModelState Error. Forexample

            if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
                {
                  InitialStartDate=TempDate;
                }
                 else{
                  InitialStartDate=null;
                  ModelState.AddError('Date is not right ');
              }

Is there anything like that. Please help and thanks a lot for reading all my question :)

Forexample i parse it like that

InitialStartDate= DateTime.ParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture);

and value is 1/1/201 it will throw an exception. I don't want it to throw an exception but add an Validation Error, so later in controller when i check ModelState.IsValid it returns false and i can show it in View.

      @Html.LabelFor(model => model.InitialStartDate, htmlAttributes: new { @class = "control-label col-offset-2" })
      @Html.TextBoxFor(model => model.IStartDateString, new { @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" })
      @Html.ValidationMessageFor(model => model.InitialStartDate, "", new { @class = "text-danger" })

I am Setting its value from view.

With All other Properties in my model. I have this

       [DataType(DataType.Date)]
       public DateTime? StartTime { get; set; }

Upvotes: 1

Views: 353

Answers (2)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Use try-catch block and add ModelState.AddModelError into your code:

View

<script type="text/javascript">
    $(document).ready(function() {
        $("#initialstartdate").datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'MM/dd/yyyy',
            minDate: 0,
            defaultDate: null
            // see jQuery datepicker docs for more attributes
        }).change(function() {
            $(this).valid(); // validation test
        });
    });
</script>

<!-- EditorFor used to include datetime as is -->
@Html.EditorFor(model => model.IStartDateString, new { @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" });

Controller

try {
        if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
        {
             InitialStartDate=TempDate;
        }
        else 
        {
             InitialStartDate = null;
             ModelState.AddModelError("Date is not right");
        }
}
catch (ArgumentException e)
{
    ModelState.AddModelError("Date is not right");
}

ModelState.AddModelError will invalidate the ModelState and as a result IsValid property becomes false when returning your view.

Probably this is far from your current needs, thus any suggestions welcome.

Upvotes: 0

Faisal Shahzad
Faisal Shahzad

Reputation: 168

Try this

$(function() {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '2011:2037',
        dateFormat: 'dd/mm/yy',
        minDate: 0,
        defaultDate: null
    }).on('change', function() {
        $(this).valid();  // triggers the validation test
        // '$(this)' refers to '$("#datepicker")'
    });
});

I hope it will be helpful for you.

Upvotes: 1

Related Questions