MVC 3 自定义验证 ValidationAttribute, IClientValidatable

CS 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Vad
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public sealed class TelPho : ValidationAttribute, IClientValidatable
    {//电话和手机必须填写一个
        private string _other;
        private string _othername;

        public string Other
        {
            get { return _other; }
            set { _other = value; }
        }

        public string Othername
        {
            get { return _othername; }
            set { _othername = value; }
        }

        private const string _defaultErrorMessage = "{0}或{1}必须填写一个";

        public TelPho() : base(_defaultErrorMessage)
        {

        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(_defaultErrorMessage, name, _othername);
        }

        protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
        {
            var ot = validationContext.ObjectType.GetProperty(Other);
            if (ot == null)
            {
                var message = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(message);
            }
            string strOther = (string)ot.GetValue(validationContext.ObjectInstance, null);

            string strVal = (string)value;
            if (String.IsNullOrEmpty(strOther) && string.IsNullOrEmpty(strVal))
            {
                var message = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(message);
            }
            return ValidationResult.Success;
        }


        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = String.Format(this.ErrorMessageString, metadata.DisplayName, _othername),
                ValidationType = "telpho"
            };
            rule.ValidationParameters["other"] = this._other;
            //rule.ValidationParameters["othername"] = this._othername;
            yield return rule;
        }
    }

    //定义值的范围
    public sealed class PriceAttribute : ValidationAttribute, IClientValidatable
    {
        public double MinPrice { get; set; }
        public double MaxPrice { get; set; }

        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            var price = (double)value;
            if (price < MinPrice || price > MaxPrice)
            {
                return false;
            }
            double cents = price - Math.Floor(price);
            if (cents < 0.99 || cents >= 0.995)
            {
                return false;
            }

            return true;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "price" //以js对应
            };
            rule.ValidationParameters["min"]= this.MinPrice;
            rule.ValidationParameters["max"]= this.MaxPrice;

            yield return rule;
        }

    } 
}

Js 代码

    <script type="text/javascript">
        $.validator.addMethod("telpho", function (value, element, params) {
            var other = params.other;
            if (this.optional(element) && $.trim($("#" + other).val()) == "")
                return false;
            else 
                return true;
        });

        $.validator.unobtrusive.adapters.add("telpho", ["other"], function (options) {
            options.rules['telpho'] = {
                other: options.params.other
            };
            options.messages['telpho'] = options.message;
        });

        //
        $.validator.addMethod("price", function (value, element, params) {
            //判断是否为空 是 为true
            if (this.optional(element)) {
                return true;
            }
            var minValue = parseFloat(params.min);
            var maxValue = parseFloat(params.max);

            console.log("minValue=" + minValue);
            console.log("maxValue=" + maxValue);
            console.log( value > minValue && value < maxValue);
            if (value > minValue && value < maxValue) {
                var cents = value - Math.floor(value);
                if (cents >= 0.99 && cents < 0.995) {
                    return true;
                }
            }
            return false;
        });

        $.validator.unobtrusive.adapters.add("price", ["min", "max"], function (options) {
            options.rules['price'] = {
                min: options.params.min,
                max: options.params.max
            };
            options.messages['price'] = options.message;
        });
    </script>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值