您现在的位置是:网站首页> .NET Core
Asp.Net Core 客户端验证和远程验证
- .NET Core
- 2022-02-05
- 696人已阅读
我们先来看这样一个注册页面和它的后台Model
复制代码
@model RegisterViewModel
@{
ViewBag.Title = "用户注册";
}
<h1>用户注册</h1>
<div class="row">
<div class="col-md-12">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="City"></label>
<input asp-for="City" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">注册</button>
</form>
</div>
</div>
复制代码
复制代码
public class RegisterViewModel
{
[Required]
[Display(Name = "邮箱地址")]
[EmailAddress]
[Remote(action: "IsEmailInUse", controller: "Account")]public string Email { get; set; }
[Required]
[Display(Name = "密码")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password",
ErrorMessage = "密码与确认密码不一致,请重新输入.")]
public string ConfirmPassword { get; set; }
public string City { get; set; }
}
复制代码
如果我们点击了注册,校验过程是发送了请求到服务器,在服务器端进行校验,这在某个程度上来说影响了用户体验和系统性能。所以我们需要在提交到服务器前先在客户端进行验证。那么怎么做呢,在Asp.Net Core上很简单。
实现客户端校验只需要添加三个js库即可,分别是:
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/jquery-validate/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js">
我们可以通过libman来很方便的添加:
复制代码
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "twitter-bootstrap@4.3.1",
"destination": "wwwroot/lib/twitter-bootstrap/"
},
{
"library": "jquery@3.4.1",
"destination": "wwwroot/lib/jquery/"
},
{
"library": "jquery-validate@1.19.1",
"destination": "wwwroot/lib/jquery-validate/"
},
{
"library": "jquery-validation-unobtrusive@3.2.11",
"destination": "wwwroot/lib/jquery-validation-unobtrusive/"
}
]
复制代码
而有些时候在注册的时候需要检测所填入的邮箱是否已经被使用,这通常是使用Ajax来进行验证,当然,在Asp.Net Core中,这个验证写法变得异常简单,同样的是需要前面三个js库,然后需要做的是在模型的Email字段上添加属性
[Remote(action: "IsEmailInUse", controller: "Account")]
然后创建对应的controller和action
复制代码
[AcceptVerbs("Get", "Post")]
[AllowAnonymous]
public async Task<IActionResult> IsEmailInUse(string email)
{
var user = await userManager.FindByEmailAsync(email);
if (user == null)
{
return Json(true);
}
else
{
return Json($"邮箱: {email} 已经被注册使用了。");
}
}
复制代码
这样就可以了。
上一篇:.NET Core 基础知识