如何仅删除一页的必填字段?我正在使用Razor页面。我希望对密码,用户名等进行相同的验证,但没有必需的验证。预先感谢!
对于条件必需属性,您可以自定义RequiredIfTrue
属性,如下所示:
RequiredIfTrueAttribute
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; }
}
PageModel
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();
}
}
[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");}
}
自定义客户端验证,必选Iftrue.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>