上图先看下效果

样式先不说,先了解下数据验证是怎么实现的

一 必须是强类型的视图

二 这些显示提示的话语,都在强类型的实体中

三 必须使用Html.BeginForm或者Html.AjaxBeginForm

四 提交方式必须是form的submit

上代码

@model FuturesContest.ViewModel.User.UserViewModel
@{
Layout = null;
} <!DOCTYPE html> <html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>期货大赛管理后台登录! | </title>
<!-- Bootstrap -->
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<!-- Font Awesome -->
<link href="~/Content/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<!-- NProgress -->
<link href="~/Content/vendors/nprogress/nprogress.css" rel="stylesheet">
<!-- Animate.css -->
<link href="~/Content/vendors/animate.css/animate.min.css" rel="stylesheet">
<!--poshytip.css-->
<link href="~/Content/vendors/poshytip-1.2/src/tip-yellow/tip-yellow.css" rel="stylesheet" />
<!-- Custom Theme Style -->
<link href="~/Content/Gentelella/custom.min.css" rel="stylesheet" />
</head>
<body class="login">
<div>
<a class="hiddenanchor" id="signup"></a>
<a class="hiddenanchor" id="signin"></a>
<div class="login_wrapper">
<div class="animate login_form">
<section class="login_content">
@{
Html.EnableClientValidation();
}
@using (Html.BeginForm("Index", "Login", FormMethod.Post))
{
<h1>期货大赛管理后台</h1>
<div>
@Html.TextBoxFor(m => m.Account, new {@class = "form-control", placeholder = "用户名", autocomplete="off"})
@Html.ValidationMessageFor(m => m.Account)
</div>
<div>
@Html.PasswordFor(m => m.Password, new {@class = "form-control", placeholder = "密码", autocomplete = "off" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<div>
<a id="sub_login" class="btn btn-default submit">登 录</a>
</div>
<div class="clearfix"></div>
}
</section>
</div>
</div>
</div>
</body>
</html>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Content/vendors/poshytip-1.2/src/jquery.poshytip.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/common.js"></script>
<script type="text/javascript">
$("#sub_login").click(function() {
$("form").submit();
}); document.onkeydown = function() {
if (event.keyCode === 13) {
$("form").submit();
}
}
</script>
          @{
Html.EnableClientValidation();
}

启动客户端验证

@using (Html.BeginForm("Index", "Login", FormMethod.Post))

benginForm提交

               @Html.TextBoxFor(m => m.Account, new {@class = "form-control", placeholder = "用户名", autocomplete="off"})
@Html.ValidationMessageFor(m => m.Account)
ValidationMessageFor错误信息会显示在这里
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Content/vendors/poshytip-1.2/src/jquery.poshytip.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/common.js"></script>

千万不要忘记unobtrusive.js


后台

[HttpPost]
public ActionResult Index(UserViewModel user)
{
var model = user.ToEntity(); if (!_bll.IsRightPassword(model))
ModelState.AddModelError("Password", "密码错误或该用户被禁用");
if (!ModelState.IsValid)
return View(user); //登录成功,将登录信息存入session
var loginInfo = _bll.GetUserByAccount(model.Account);
Session["LoginInfo"] = loginInfo;
//将登录信息存储到cookies
_bll.SaveCookie(loginInfo); return RedirectToAction("Index", "Back");
}

ModelState.AddModelError 可以添加一个错误信息

ModelState.IsValid 表示所有数据通过验证

在看看viewModel验证的几种类型

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc; namespace FuturesContest.ViewModel.User
{
public class UserAddViewModel
{
public int Id { get; set; } [DisplayName("用户名")]
[Required(ErrorMessage = "{0}不能为空")]
[Remote("CheckAccount", "Back", ErrorMessage = "{0}已存在")]
public string Account { get; set; } [DisplayName("密码")]
[Required(ErrorMessage = "{0}不能为空")]
[RegularExpression(@"^[0-9A-Za-z]{6,20}$",ErrorMessage = "{0}格式为6-20位字母或数字")]
public string Password { get; set; } [DisplayName("昵称")]
[Required(ErrorMessage = "{0}不能为空")]
[Remote("CheckNickName", "Back", ErrorMessage = "{0}已存在")]
public string NickName { get; set; } [DisplayName("有效状态")]
public int IsEnabled { get; set; } [DisplayName("创建时间")]
public DateTime AddTime { get; set; } [DisplayName("最后登录时间")]
public DateTime LastTime { get; set; } [DisplayName("头像")]
public string HeadThumb { get; set; } [DisplayName("排序")]
[Required(ErrorMessage = "{0}不能为空")]
[Range(, , ErrorMessage="{0}取值范围为0-99")]
public int OrderId { get; set; }
}
}

DisplayName-------------- 在用labelFor的时候,会显示后面的名称

[Required(ErrorMessage = "{0}不能为空")] ------------非空验证

[Remote("CheckAccount", "Back", ErrorMessage = "{0}已存在")] ---------Ajax验证,需要后台有一个CheckAccount的方法

[RegularExpression(@"^[0-9A-Za-z]{6,20}$",ErrorMessage = "{0}格式为6-20位字母或数字")]----------正则验证

[Range(0, 99, ErrorMessage="{0}取值范围为0-99")]------------范围验证

ajax验证的案例

     //Ajax验证用户名是否存在
public JsonResult CheckAccount(string account)
{
var result = _bll.ExistAccount(account);
return Json(result, JsonRequestBehavior.AllowGet);
}

返回的一定是一个布尔值,才能知道是否通过


好啦!现在应该已经可以正常的显示数据验证的错误信息了!但样式不好看,所以我们要修改样式

我用的是poshytip插件,类似于tips的插件

引入对应的css和js

修改源码

找到jquery.validate.unobtrusive.js

找到function onError(error, inputElement)函数,稍微改改就可以 我贴个全的

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

这样我们就解决了通过微软的这个js进行前端验证的样式修改

注意:这种验证没有到服务器验证,只是JS拦截

但!!!!还是不够,Ajax方法的后台验证样式并不通过这个js,它是后端验证,直接返回到前端的

所以我封装了一个js,捕获返回的数据进行修改

common,js

$(function () {
$(".field-validation-error").each(function () {
var $this = $(this);
var thisid = $this.attr("data-valmsg-for").replace(".", "_");
var direction = "right";
// 左边+元素宽+提示的文字+提示两边的空白
if (($this[0].offsetLeft + $this.width() + $this.text().length * 10 + 20) > $(document).width()) {
direction = "left";
}
$this.hide(); setTimeout(function () {
$("#" + thisid).poshytip({
content: $this.text(),
alignTo: 'target',
alignX: direction,
alignY: 'center',
showOn: 'none',
offsetX: 5
}).poshytip('show');
}, 100); });
});

到这时,我们才完成了MVC的数据验证!!!

 

期货大赛项目|四,MVC的数据验证的更多相关文章

  1. 期货大赛项目|十,MVC对js和css的压缩

    在Global.asax中添加两行代码 //默认在调试期间,不会启用js和css的压缩 //下面的语句确保了在调试期间也压缩css和js BundleTable.EnableOptimizations ...

  2. MVC中数据验证

    http://www.studyofnet.com/news/339.html http://www.cnblogs.com/kissdodog/archive/2013/05/04/3060278. ...

  3. <转>ASP.NET学习笔记之MVC 3 数据验证 Model Validation 详解

    MVC 3 数据验证 Model Validation 详解  再附加一些比较好的验证详解:(以下均为引用) 1.asp.net mvc3 的数据验证(一) - zhangkai2237 - 博客园 ...

  4. MVC 多种 数据验证 post

    技术:c# .net  采用mvc框架,实现model的数据验证. 刚开始觉得数据验证很方便,可以判断非空.数据正确性,但是后来发现很多需要数据库的判定还是需要post请求做,但是就想mvc的数据验证 ...

  5. MVC Model数据验证

    概述 上节我们学习了Model的数据在界面之间的传递,但是很多时候,我们在数据传递的时候为了确保数据的有效性,不得不给Model的相关属性做基本的数据验证. 本节我们就学习如何使用 System.Co ...

  6. ASP.NET MVC 扩展数据验证 转

    此文只作记录 public class MaxWordsAttribute : ValidationAttribute { public MaxWordsAttribute(int maxWords) ...

  7. MVC 3 数据验证 Model Validation 详解

    在MVC 3中 数据验证,已经应用的非常普遍,我们在web form时代需要在View端通过js来验证每个需要验证的控件值,并且这种验证的可用性很低.但是来到了MVC 新时代,我们可以通过MVC提供的 ...

  8. [转]MVC自定义数据验证(两个时间的比较)

    本文转自:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html Model: public class Model ...

  9. (转)MVC 3 数据验证 Model Validation 详解

    继续我们前面所说的知识点进行下一个知识点的分析,这一次我们来说明一下数据验证.其实这是个很容易理解并掌握的地方,但是这会浪费大家狠多的时间,所以我来总结整理一下,节约一下大家宝贵的时间. 在MVC 3 ...

随机推荐

  1. 两张图概括struts2执行流程核心(经典)

  2. Unity3D之通过C#使用Advanced CSharp Messenger

    Advanced CSharp Messenger 属于C#事件的一种. 维基百科中由详细的说明http://wiki.unity3d.com/index.php?title=Advanced_CSh ...

  3. node ,npm和nvm 版本的管理

    node npm :node 的包管理 nvm :node 的版本管理 node -v ---->查看node 的版本  (v---->version) npm -v ----->n ...

  4. Git系列①之仓库管理互联网托管平台github.com的使用

    互联网项目托管平台github.com的使用 1.安装git客户端 # yum install -y git 配置git全局用户以及邮箱 [root@web01 ~]# git config --gl ...

  5. linux无法启动httpd服务问题

    httpd 服务启动报错,可能出现的问题比较多,通过查看日志看是什么报错 (tail  200f /etc/httpd/logs/error_log) 1.查看防火墙是不是关闭状态 2.查看80端口是 ...

  6. 51nod--1298 (计算几何基础)

    题目: 1298 圆与三角形 题目来源: HackerRank 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注 给出圆的圆心和半径,以及三角形的三个顶点,问圆 ...

  7. 如何保障Web应用安全性

    通过加密算法对关键数据进行加密 通过过滤器防御跨站脚本攻击XSS.跨域请求伪造CRSF和SQL注入 通过安全框架( Shiro.Spring Security )进行认证和授权 设置IP黑白名单来进行 ...

  8. VUE 多页面配置(一)

    1. 概述 1.1 说明 项目开发过程中会遇到需要多个主页展示情况,故在vue单页面的基础上进行配置多页面开发以满足此需求. 2. 实例 2.1 页面配置 2.1.1 默认首页 使用vue脚手架搭建后 ...

  9. Swift 学习- 04 -- 字符串和字符

    // 字符串 和 字符 // 字符串 是有序的 Character (字符) 类型的值的集合,  通过 String 类型的集合 // swift 的 String 和 Character 类型提供了 ...

  10. 1005:Number Sequence(hdu,数学规律题)

    Problem Description A number sequence is defined as follows: f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1 ...