期货大赛项目|四,MVC的数据验证

上图先看下效果

期货大赛项目|四,MVC的数据验证

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

一 必须是强类型的视图

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

三 必须使用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 WebApi 用户验证 (2)


下一篇:ASP.NET MVC 扩展数据验证 转