1.修改jquery.validate.unobtrusive.js

将onError方法修改

 //修改的部分
/////////////////////////////////////////////////////////////////// function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
//add
var $customErrorTip = container.attr("data-forerrortip");
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
//add
var elem = $("#" + inputElement[].name.replace(".", "_"));//添加提示消息
if (replace) {
container.empty();
//add start
if (error.html() != "") {
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip("destroy");
} else {
elem.poshytip("destroy");
}
var direction = "right";
//左边+元素宽+提示的文字+提示两边的空白
if ((elem[].offsetLeft + elem.width() + error.length * + ) > $(document).width()) {
direction = "left";
}
var errorConfig = {
content: error,
alignTo: 'target',
alignX: direction,
alignY: 'center',
showOn: 'none',
bgImageFrameSize: ,
offsetX:
};
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip(errorConfig).poshytip('show');
} else {
elem.filter(':not(.valid)').poshytip(errorConfig).poshytip('show');
}
} else {
if ($customErrorTip) {
$("#" + $customErrorTip).poshytip("destroy");
} else {
elem.poshytip("destroy");
}
}
//add end
//update disable
//error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
} ///////////////////////////////////////////////////////////////////////////////////

2.Index.cshtml页面

@model MvcApplication1.Models.UserViewModel

@{
ViewBag.Title = "Index"; }
<link href="~/Content/poshytip/tip-yellow/tip-yellow.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Content/poshytip/jquery.poshytip.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script> <script type="text/javascript">
function showTip(objJq, msg) {
objJq.poshytip('destroy');
if (!objJq.data("poshytip")) {
objJq.poshytip({
showOn: 'none',
alignTo: 'target',
alignX: 'right',
alignY: 'center',
offsetX: 5,
className: 'tip-yellow',
content:msg
});
objJq.focus(function () {
$(this).poshytip('hide');
});
objJq.data("poshytip").$tip.click(function () {
$(this).hide();
});
}
objJq.poshytip('show');
}
$(function () {
$("#btnTest").click(function () {
if ($("#myfrom").valid()) {
$.post("@Url.Action("Create","Home")", $("#myfrom").serializeArray(), function (data) {
if (data.Status==3) {
$(data.Msg).each(function () {
var item = $('#' + this.Key);
showTip(item, this.Value);
});
} else {
alert(data);
}
});
}
});
}); </script> @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "myfrom" }))
{ <label>用户名:</label> @Html.TextBoxFor(u => u.UserName)@Html.ValidationMessageFor(u => u.UserName)
<br />
<label>性别:</label>@*
@Html.RadioButtonFor(u=>u.Sex,1,new{ @checked="checked"})@:男*@
@Html.RadioButtonFor(u=>u.Sex,1)@:男
@Html.RadioButtonFor(u=>u.Sex,2)@:女
<span id="groupRadioErrorSex" style="vertical-align:middle;line-height:70px;">&nbsp;</span>
@Html.ValidationMessageFor(u => u.Sex,"", new{data_forErrorTip="groupRadioErrorSex" })
<br />
<input type="button" value="提交" id="btnTest" />
}

3.HomeController

public class HomeController : Controller
{
//
// GET: /Home/ public ActionResult Index()
{
return View(new UserViewModel() { IsEnable = false, UserCode = "aa" });
} [HttpPost]
public ActionResult Create(UserViewModel model)
{
//移除添加了Request属性,却又不需要验证的属性
ModelState.Remove("UserCode");
ModelState.Remove("UserPwd");
ModelState.Remove("County");
if (!ModelState.IsValid)
{
//服务器端自定义添加错误验证
ModelState.AddModelError("UserName", "您输入的账号已被使用");
return Json(new { Status = , Msg = ModelState.GetErrorsDict() });
}
return Json("ok");
} /// <summary>
/// 远程验证用户名
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public ActionResult GetUser(string username)
{
return Json(!username.ToLower().Equals("admin"),JsonRequestBehavior.AllowGet);//返回True表示通过验证,返回False表示不通过验证
}
} public static class HelperExtensions
{ public static List<KeyValuePair<string, string>> GetErrorsDict(this ModelStateDictionary modelState)
{
var errorList = (from item in modelState
where item.Value.Errors.Any()
select new KeyValuePair<string, string>(item.Key, item.Value.Errors[].ErrorMessage)).ToList(); return errorList;
}
}

4.UserViewModel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc; namespace MvcApplication1.Models
{
public class UserViewModel
{ /// <summary>
/// Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// FK-用户级别ID
/// </summary>
[Required(AllowEmptyStrings = false, ErrorMessage = "请选择用户等级")]
public int LevelId { get; set; }
/// <summary>
/// 用户类型 详见文档
/// </summary>
public int Type { get; set; }
/// <summary>
/// 用户编号
/// </summary>
[Required()]
public string UserCode { get; set; }
/// <summary>
/// 用户名
/// </summary>
[Required(ErrorMessage = "用户名必需填写")]
[MobileOrEmail(ErrorMessage="输入手机号或邮箱")]
[StringLength(, ErrorMessage = "用户名最大不能超过50个字符")]
[Remote("GetUser", "Home", ErrorMessage = "该姓名已存在")]
public string UserName { get; set; }
/// <summary>
/// 密码
/// </summary>
[Required(ErrorMessage = "密码不能为空")]
public string UserPwd { get; set; }
/// <summary>
/// 确认密码
/// </summary>
public string ConfirmUserPwd { get; set; }
/// <summary>
/// 第三方绑定会员ID
/// </summary>
public string ThirdSiteUserId { get; set; }
/// <summary>
/// 真实姓名
/// </summary>
public string TrueName { get; set; }
/// <summary>
/// 昵称
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 头像
/// </summary>
public string UserAvatar { get; set; }
/// <summary>
/// 省
/// </summary>
public string Province { get; set; }
/// <summary>
/// 市
/// </summary>
public string City { get; set; }
/// <summary>
/// 区县
/// </summary>
[Required(ErrorMessage="不能为空")]
[System.ComponentModel.DataAnnotations.Compare("City")]
public string County { get; set; }
/// <summary>
/// 地址
/// </summary>
public string Address { get; set; }
/// <summary>
/// 邮编
/// </summary>
public string Zip { get; set; }
/// <summary>
/// 电话
/// </summary>
public string Tel { get; set; }
/// <summary>
/// 手机
/// </summary>
[RegularExpression(@"^1[3|4|5|8][0-9]\d{8}$", ErrorMessage = "手机格式错误")]
public string Mobile { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 性别
/// </summary>
[Required(ErrorMessage="请选择性别")]
public string Sex { get; set; }
/// <summary>
/// 出生日期
/// </summary>
public Nullable<System.DateTime> Birthday { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnable { get; set; } public SelectList UserLevelList { get; set; }
public IList<SelectListItem> ProvinceList { get; set; } } /// <summary>
/// 自定义验证属性,手机号或者邮箱
/// </summary>
public class MobileOrEmailAttribute : RegularExpressionAttribute, IClientValidatable
{
public MobileOrEmailAttribute()
: base(RegexHelper.MobileOrEmailPattern) { } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "regex",
ErrorMessage = ErrorMessage,
}; rule.ValidationParameters.Add("pattern", Pattern);
yield return rule;
}
} public static class RegexHelper
{
public static readonly string SlugPattern = @"(^[a-z0-9])([a-z0-9-]+)*([a-z0-9])$";
public static readonly Regex SlugRegex = new Regex(SlugPattern); public static readonly string SlugWithSegmentsPattern = @"^(?!-)[a-z0-9-]+(?<!-)(/(?!-)[a-z0-9-]+(?<!-))*$";
public static readonly Regex SlugWithSegmentsRegex = new Regex(SlugWithSegmentsPattern); public static readonly string IpAddressPattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
public static readonly Regex IpAddressRegex = new Regex(IpAddressPattern); public static readonly string MobilePattern = @"^1[3|4|5|8][0-9]\d{8}$";
public static readonly Regex MobileRegex = new Regex(MobilePattern); // 密码必需由英文字母、数字或特殊符号组成 6~16个字符,区分大小写
public static readonly string PasswordPattern = @"^[\w~!@#$%^&*()_+|{}:""<>?`\-=\\[\];',./]{6,16}$";
public static readonly Regex PasswordRegex = new Regex(PasswordPattern); public static readonly string EmailPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
public static readonly Regex EmailRegex = new Regex(EmailPattern); public static readonly string UrlPattern = @"^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$";
public static readonly Regex UrlRegex = new Regex(UrlPattern); public static readonly string NumberPattern = @"^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$";
public static readonly Regex NumberRegex = new Regex(NumberPattern); public static readonly string MobileOrEmailPattern = string.Format("({0}|({1}))", MobilePattern, EmailPattern);
}
}

ASP.NET MVC 3 使用Model自定义验证的样式的更多相关文章

  1. ASP.NET MVC中对Model进行分步验证的解决方法

    原文:ASP.NET MVC中对Model进行分步验证的解决方法 在我之前的文章:ASP.NET MVC2.0结合WF4.0实现用户多步注册流程中将一个用户的注册分成了四步,而这四个步骤都是在完善一个 ...

  2. ASP.NET MVC下的四种验证编程方式

    ASP.NET MVC采用Model绑定为目标Action生成了相应的参数列表,但是在真正执行目标Action方法之前,还需要对绑定的参数实施验证以确保其有效性,我们将针对参数的验证成为Model绑定 ...

  3. ASP.NET MVC 中如何用自定义 Handler 来处理来自 AJAX 请求的 HttpRequestValidationException 错误

    今天我们的项目遇到问题 为了避免跨站点脚本攻击, 默认我们项目是启用了 validateRequest,这也是 ASP.NET 的默认验证规则.项目发布后,如果 customError 启用了,则会显 ...

  4. ASP.NET MVC下的四种验证编程方式【转】

    ASP.NET MVC采用Model绑定为目标Action生成了相应的参数列表,但是在真正执行目标Action方法之前,还需要对绑定的参数实施验证以确保其有效 性,我们将针对参数的验证成为Model绑 ...

  5. ASP.NET MVC下的四种验证编程方式[续篇]

    在<ASP.NET MVC下的四种验证编程方式>一文中我们介绍了ASP.NET MVC支持的四种服务端验证的编程方式("手工验证"."标注Validation ...

  6. ASP.NET MVC下的四种验证编程方式[续篇]【转】

    在<ASP.NET MVC下的四种验证编程方式> 一文中我们介绍了ASP.NET MVC支持的四种服务端验证的编程方式(“手工验证”.“标注ValidationAttribute特性”.“ ...

  7. ASP.NET MVC 学习笔记-7.自定义配置信息 ASP.NET MVC 学习笔记-6.异步控制器 ASP.NET MVC 学习笔记-5.Controller与View的数据传递 ASP.NET MVC 学习笔记-4.ASP.NET MVC中Ajax的应用 ASP.NET MVC 学习笔记-3.面向对象设计原则

    ASP.NET MVC 学习笔记-7.自定义配置信息   ASP.NET程序中的web.config文件中,在appSettings这个配置节中能够保存一些配置,比如, 1 <appSettin ...

  8. ASP.NET MVC中默认Model Binder绑定Action参数为List、Dictionary等集合的实例

    在实际的ASP.NET mvc项目开发中,有时会遇到一个参数是一个List.Dictionary等集合类型的情况,默认的情况ASP.NET MVC框架是怎么为我们绑定ASP.NET MVC的Actio ...

  9. asp.net MVC中的@model与Model

    asp.net MVC中的@model与Model https://blog.csdn.net/ydm19891101/article/details/44301201 在MVC的实际使用中,我们经常 ...

随机推荐

  1. 代码重构-2 简单不变的 if else 用字典代替

    原代码 private string GetExDesc(string lotteryCode) { string exDesc = "抽奖"; if (lotteryCode.T ...

  2. 代码重构-1 对参数中有 bool值的拆分

    最近对一个同事的代码进行重构 第1步 对参数中有 bool值的拆分 原代码如下: private bool CheckIsInFreeTimes(GetDataForValidateLotteryRe ...

  3. Java初学(三)

    一.使用键盘录入数据 三步:1.导入包:import  java.util.Scanner; 2.创建键盘录入对象:Scanner sc=new  Scanner(System.in);   3.通过 ...

  4. unity3d DefineManager 全局宏定义

    /** * Editor Wizard for easily managing global defines in Unity * Place in Assets/Editor folder, or ...

  5. IOS学习笔记—苹果推送机制APNs

    转自:唐韧_Ryan http://blog.csdn.net/ryantang03/article/details/8482259 推送是解决轮询所造成的流量消耗和 电量消耗的一个比较好的解决方案, ...

  6. SQL2005删除复制数据库的发布与订阅的方法(转载)

    SQL2005删除复制数据库的发布与订阅的方法 --在测试环境中恢复从正式数据库服务器 上备份下来的bak文件后,正式环境里数据库复制的发布.订阅也被带进来了,结果恢复的数据库无法更改表结构,直接删除 ...

  7. cad2013

    ## ribbon界面? ribbon界面是一种设计ui, 可以认为是传统的  菜单和工具栏  组合. 是 用于 实时显示 + 面向结果的 设计ui 但并不是所有的程序都适合.  ribbon 并不是 ...

  8. 【整理】Angularjs 监听ng-repeat onfinishrender事件

    http://stackoverflow.com/questions/15207788/calling-a-function-when-ng-repeat-has-finished http://ww ...

  9. 采用Unity快速开发高质量游戏的若干优化建议

    http://files.cnblogs.com/123ing/%E9%87%87%E7%94%A8Unity%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E9%AB%98 ...

  10. [POJ1157]LITTLE SHOP OF FLOWERS

    [POJ1157]LITTLE SHOP OF FLOWERS 试题描述 You want to arrange the window of your flower shop in a most pl ...