MVC视图模型扩展自定义验证让kendoUI 前端支持

  • 发布日期:2016年3月11日
  • 新闻类别: KendoUI
  • 查看:530

网站开发中的表单经常的验证码,要找很正则集成,不过视图是直接支持正则的,但是一个大项目会有多处用到相同的正则,这样就会很多重复了,一般多处用到些正则表达式,最好的做法是扩展自定义验正,下面以手机号码验证为例,验证主要分为服务端与客户端两部份,所以要实现前端的验证,还需要扩展前端的部分

C#部份:


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace WenDa.Models
{
    public class ChinaMobileAttribute : ValidationAttribute, IClientValidatable
    {

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                string email = value.ToString();

                if (Regex.IsMatch(email, @"^0{0,1}(13[0-9]|15[0-9]|153|170|178|18[0-9])[0-9]{8}$", RegexOptions.IgnoreCase))
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult(string.Format(Resources.Validation.CheckFormat, validationContext.DisplayName));
                }
            }
            return ValidationResult.Success;
        }       
       
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule()
            {
                ValidationType = "chinamobile",
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
            };

        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(Resources.Validation.CheckFormat, name);
        }

    }
}

 

客户端部份:


$.validator.addMethod('chinamobile', function(value, element)
       {
           return/^0{0,1}(13[0-9]|15[7-9]|153|156|178|18[0-9])[0-9]{8}$/.test(value)           
       });

 $.validator.unobtrusive.adapters.addBool("chinamobile");

kendo ui 客户端扩展支持:


(function ($, kendo) {
            $.extend(true, kendo.ui.validator, {
                rules: { // custom rules
                    chinamobile: function (input, params) {
                        if (input.is("[name='Mobile']") && input.val() != "") {
                            //input.attr("data-productnamevalidation-msg", "Product Name should start with capital letter");
                            return /^0{0,1}(13[0-9]|15[0-9]|153|170|178|18[0-9])[0-9]{8}$/.test(input.val());
                        }
                        return true;
                    }
                },
                messages: { //custom rules messages
                    chinamobile: function (input) {
                        // return the message text
                        return input.attr("data-val-chinamobile");
                    }
                }
            });
        })(jQuery, kendo);