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

后端 未结 2 362
广开言路
广开言路 2020-12-30 12:10

I am new to ASP.Net MVC 3, facing some issues while trying to implementing client side unobtrusive validation for a editor template I have created for showing date in a cust

2条回答
  •  -上瘾入骨i
    2020-12-30 13:03

    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;
    }, '');
    

提交回复
热议问题