上图先看下效果

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

一 必须是强类型的视图

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

三 必须使用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. Python运维开发基础04-语法基础【转】

    上节作业回顾(讲解+温习90分钟) #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author:Mr.chen # 仅用列表+循环实现“简单的购物车程 ...

  2. requests库入门04-http基本认证

    因为后续样例中GitHub都需要提供认证,所以先写关于基本认证的 http的请求中,有一些请求是需要通过授权认证之后才会响应,授权认证就是检查用户名和密码的过程.http有一个基本认证方式,在认证的过 ...

  3. windows下django1.7 +python3.4.2搭建记录1

    python+django在linux下搭建比较简单,windows下搭建比较复杂,所以列在下方一.下载安装下载django的包,到刚解压后的Django-1.7目录下执行命令 python setu ...

  4. 032_nginx配置文件安全下载

    一. server { listen 8866; server_name _; access_log /usr/local/etc/nginx/log/download.access.log main ...

  5. $Django 路飞之小知识回顾,Vue之样式element-ui,Vue绑定图片--mounted页面挂载--路由携带参数

    一 小知识回顾 1 级联删除问题 2 一张表关联多个表,比如有manytomanyfileds forignkey,基于对象查询存在的问题:反向查询的时候  表名小写_set.all()不知是哪个字段 ...

  6. Linux/Ubuntu安装搜狗输入法

    零.你首先需要安装fcitx小企鹅输入法,相信绝大部分用linux的中国人都用这个输入法,安装fcitx后同时还能解决Sublime Text的中文输入问题. 安装fcitx输入法前首先要安装fcit ...

  7. Light OJ 1102

    题意: 给你一个数 N , 求分成 K 个数 (可以为 0 ) 的种数: 思路: 类似 在K个抽屉放入 N 个苹果, 不为0, 就是 在 n-1 个空隙中选 m-1个: 为 0, 就可以先在 K 个抽 ...

  8. <转载>bellman-ford算法

    转载来源:https://www.cnblogs.com/tanky_woo/archive/2011/01/17/1937728.html 相关文章: 1.Dijkstra算法: http://ww ...

  9. iOS9 新功能:Support Universal Links,iOS10 openUrl新函数

    先看官方文档:https://developer.apple.com/library/ios/documentation/General/Conceptual/AppSearch/UniversalL ...

  10. 5)django-模板

    django模板显示页面 一:语法使用 1)变量:{{变量名}}         2)for循环            {% for row in userlist%}                 ...