ASP.NET MVC4 实体验证-----限定输入长度

 

前台页面代码:

@{
    ViewBag.Title = "资源库-用户添加页";
    //指定布局页
    Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";
}

@using (Html.BeginForm())
{    
    <div class="m-content">
        <div class="m-form f-cb">
            <dl class="f-cb s-borderbg">

                <dt><i>*</i>登录名:</dt>
                <dd>
                    @Html.TextBoxFor(model => model.CLOGINNAME, new { @class = "u-iptm", @maxlength = "25" })
                    @Html.ValidationMessageFor(model => model.CLOGINNAME)
                </dd>

                <dt><i>*</i>密码:</dt>
                <dd>
                    @Html.TextBoxFor(model => model.CPASSWORD, new { @class = "u-iptm", Value = "123456", @maxlength = "25" })
                    @Html.ValidationMessageFor(model => model.CPASSWORD)
                </dd>

                <dt></dt>
                <dd>
                    <input type="submit" value="保存" class="u-btnblue" />
                    <input type="button" value="取消" class="u-btnblue marl10" οnclick="location.href='/admin/user/index';" />
                </dd>
            </dl>
        </div>
    </div>
}



实体类:

 

    public partial class RS_USER 
    {
        /// <summary>
        /// 
        /// </summary>
        [LengthCheck(0,12,ErrorMessage="* 不能超过12个字符!")]
	public string CLOGINNAME { get; set; }

        /// <summary>
        /// 
        /// </summary>
	public string CPASSWORD { get; set; }
}


LengthCheckAttribute.cs类:
 

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

namespace MyResource.Attributes
{
    public class LengthCheckAttribute : RangeAttribute, IClientValidatable
    {
        public LengthCheckAttribute(int minimum, int maximum) : base(minimum, maximum) { }

        //后台验证
        public override bool IsValid(object value)
        {
            bool bResult = true;
            if (value != null)
            {
                String str = (String)value;
                int length = GetByteLength(str);
                bResult = str.Length <= (int)this.Maximum;
            }
            return bResult;
        }

        //验证错误信息
        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(name);
        }

        //客户端验证
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule validationRule = new ModelClientValidationRule() { ValidationType = "lengthcheck", ErrorMessage = FormatErrorMessage(metadata.DisplayName) };
            validationRule.ValidationParameters.Add("length",this.Maximum);
            yield return validationRule;
        }

        public int GetByteLength(string str)
        {
            //使用Unicode编码的方式将字符串转换为字节数组,它将所有字符串(包括英文中文)全部以2个字节存储
            byte[] bytestr = System.Text.Encoding.Unicode.GetBytes(str);
            int j = 0;
            for (int i = 0; i < bytestr.GetLength(0); i++)
            {
                //取余2是因为字节数组中所有的双数下标的元素都是unicode字符的第一个字节
                if (i % 2 == 0)
                {
                    j++;
                }
                else
                {
                    //单数下标都是字符的第2个字节,如果一个字符第2个字节为0,则代表该Unicode字符是英文字符,否则为中文字符
                    if (bytestr[i] > 0)
                    {
                        j++;
                    }
                }
            }
            return j;
        }
    }
}


 后台Controller代码:略。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值