ASP.Net MVC 3 - Client side unobtrusive validation for Editor Templates

萝らか妹 提交于 2019-11-30 07:24:05
Shravan

After some effort, I made the control to work, putting in if it is helpful to anybody out there.

The first point is to have the control defined as

@model DateTime?

<table class="datetime">
<tr>
    <td>@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("dd") : string.Empty)) </td>
    <td class="separator">/</td>
    <td>@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM") : string.Empty))</td>
    <td class="separator">/</td>
    <td>@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("yyyy") : string.Empty))</td>
</tr>
<tr>
    <td class="label">dd</td>
    <td/>
    <td class="label">mm</td>
    <td/>
    <td class="label">yyyy</td>
</tr>
</table>

Make sure, you give empty strings as name to all the three textboxes, this forces the MVC framework to generate same name corresponding to Model DateofBirth for all the three textboxes in the client side. Also, unobtrusive javascript validation parameters would be generated for the first textbox in the list, since it is the first occurence of a edit control with the name of the model.

On the client side, on any event on any of these textboxes fires all the relevant validation events, since all these 3 textboxes have the same name.

On top of the regular validations like required,.... we have to write a custom client validation routine which would combine all these three values and checks whether the combined value forms a valid date. This can be achieved as in the answer given by Jeff.

Ok so a few things. First - if at all possible, don't split the date up into three fields. You'll save yourself a world of headache by just setting it up as a single field with some validation and maybe jQueryUI's DatePicker.

Next, in your custom attribute code inside DateTimeClientValidationAttribute, you never actually check to see if the date is valid by implementing IsValid:

protected override ValidationResult IsValid(object value, 
    ValidationContext validationContext) 
{
   ...
   // Put date parts together and check is valid...
   if (DateTime.TryParse(year+"/"+month+"/"+day, out dateResult))
      return ValidationResult.Success;

   // Not valid
   return new ValidationResult(String.Format(ErrorMessageString, 
      validationContext.DisplayName));
}

Next you'll have to create an unobtrusive validation adapter and a jQuery validator method which puts the params together and tries to parse out the date:

jQuery.validator.unobtrusive.adapters.add(
    'validdate', // notice this is coming from how you named your validation rule
    ['dayelement'],
    ['monthelement'],
    ['yearelement']
    function (options) {
        options.rules['datepartcheck'] = options.params;
        options.messages['datepartcheck'] = options.message;
    }
);
jQuery.validator.addMethod('datepartcheck', function (value, element, params) {
    var year = params[2];
    var month = params[1];
    var day = params[0];

    var birthDate = year + '/' + month-1 + '/' + day;
    var isValid = true;

    try {
        // datepicker is a part of jqueryUI.
        // include it and you can take advantage of .parseDate:
        $.datepicker.parseDate('yy/mm/dd', birthDate);
    }
    catch (error) {
        isValid = false;
    }
    return isValid;
}, '');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!