c# - 仅删除 1 页所需的验证
问题描述
如何仅删除 1 页的必填字段?我正在使用 Razor 页面。我想要对我的密码、用户名等进行相同的验证,但不需要验证。
解决方案
对于有条件的必需属性,您可以自定义RequiredIfTrue
属性,如下所示:
必需的IfTrue属性
public class RequiredIfTrueAttribute : ValidationAttribute, IClientModelValidator
{
private string PropertyName { get; set; }
public RequiredIfTrueAttribute(string propertyName)
{
PropertyName = propertyName;
ErrorMessage = "The {0} field is required."; //used if error message is not set on attribute itself
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
object instance = context.ObjectInstance;
Type type = instance.GetType();
bool.TryParse(type.GetProperty(PropertyName).GetValue(instance)?.ToString(), out bool propertyValue);
if (propertyValue && (value == null || string.IsNullOrWhiteSpace(value.ToString())))
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
object isrequired;
var viewContext = context.ActionContext as ViewContext;
viewContext.ViewData.TryGetValue(PropertyName, out isrequired);
if ((bool)isrequired)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-requirediftrue", errorMessage);
}
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
模型
public class User
{
public bool IsRequired { get; set; }
[RequiredIfTrue("IsRequired")]
[StringLength(6)]
public string UserName { get; set; }
[RequiredIfTrue("IsRequired")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
public string Password { get; set; }
public int Age { get; set; }
}
页面模型
public class UserProfile1Model : PageModel
{
[BindProperty]
public User User { get; set; }
public void OnGet()
{
User = new User { IsRequired = true };
}
public async Task<IActionResult> OnPost()
{
if (ModelState.IsValid)
{
return RedirectToPage(nameof(Index));
}
return Page();
}
}
页面,将 IsRequired 值保存到 ViewData 中判断是否在AddValidation
方法中添加验证
@page
@model RazorPages3_1.UserProfile1Model
@{
ViewData["Title"] = "UserProfile1";
ViewData["IsRequired"] = Model.User.IsRequired;
}
<form id="frm" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="User.UserName" class="control-label"></label>
<input asp-for="User.UserName" class="form-control" />
<span asp-validation-for="User.UserName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="User.Password" class="control-label"></label>
<input asp-for="User.Password" class="form-control" />
<span asp-validation-for="User.Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="User.Age" class="control-label"></label>
<input asp-for="User.Age" class="form-control" />
<span asp-validation-for="User.Age" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Create" />
</div>
</form>
@section Scripts
{
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
自定义客户端验证,requiredIftrue.validation.js
$.validator.addMethod("requirediftrue",
function (value, element, parameters) {
return value !== "" && value != null;
}
);
$.validator.unobtrusive.adapters.addBool('requirediftrue');
将其添加到 _ValidationScriptsPartial.cshtml
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/requiredIftrue/requiredIftrue.validation.js"></script>
推荐阅读
- nuget - 从 nuspec 迁移到 msbuild 以进行 nuget 打包
- node.js - 使用条件表达式“attribute_not_exists(PK)”总是解析为真
- c# - 将字节数组写入地址
- compression - IPv6 地址压缩
- react-bootstrap - How to automatically put cursor in newest row react-bootstrap-table-next
- python - Multiple version of python but only one works
- mysql - MySQL使用一个查询从至少一个表中删除行
- c - Linux recvmsg()没有从套接字获取软件时间戳
- python-venv - Apache Superset 在我的浏览器中不可用
- typescript - 是否可以在 TypeScript 中设置特定的编译目标来转换代码以获得更高的性能?