ASP.NET MVC:基于两个字段长度的DataAnnotation自定义验证



我有这个JS方法,我正在用它来做一些验证。但我想看看是否可以通过DataAnnotation构建自定义验证。有没有一种方法可以让我收集这些信息,以便在自定义验证中使用它?这会进行JS验证吗?

JS代码我想替换

function materialsconfirmhasError() {
let materialsconfirm = $('input[name="ckmaterialsconfirm"]:checked').length > 0;
let uploadcontrol = $("#upImport").data("kendoUpload"),
files = uploadcontrol.getFiles();
let FileLink = $("#txtFileLink").val();
console.log(FileLink);
if (files.length !== 0 || FileLink.length !== 0) {
if (materialsconfirm == false) {
$("#lblConfirmError").show();
return true
} else {
$("#lblConfirmError").hide();
return false
}
}
return false
}

HTML

<div id="materialsconfirm" class="form-check">
<div class="col-xs-2">
<div class="checkbox-inline">
@Html.CheckBoxFor(x => x.materialsconfirm,new { id= "ckmaterialsconfirm", @class= "form-control" })
@*<label for="ckmaterialsconfirm"> I have read and adhered to the above statements</label>*@
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-12">
<label id="lblConfirmError" class="text-danger field-validation-error" style="display:none">Please Confirm.</label>
</div>
</div>
</div>

型号

[Display(Name = "I have read and adhered to the above statements")]
[CustomMaterialValidator]
public Boolean materialsconfirm { get; set; }

自定义物料验证器

public class CustomMaterialValidator: ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
if (value != null) {
bool flgCustomMaterial = value is bool ? (bool) value : false;
if (flgCustomMaterial == true) {
return ValidationResult.Success;
} else {
}
return new ValidationResult("Please Confirm.");
}
return new ValidationResult("Please Confirm.");
}
}

您可以编写一个自定义ValidationAttribute,从模型中读取其他属性。您可以在IsValid方法的重载中使用可用的ValidationContext来执行此操作。

您可以通过以下方式访问不同的属性:

var otherPropertyInfo = validationContext.ObjectType.GetProperty("OtherPropertyName");
if (otherPropertyInfo == null) {
return new ValidationResult("The other property doesn't exist");
}
object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

在本例中,该值将在otherPropertyValue中,您可以使用该值以及注释属性的value(在您的情况下为materialsconfirm(来实现所需的验证。

您可以通过从ValidationAttribute发出具有客户端验证的信号,并为其创建一个jQuery验证器,使该属性在客户端工作,如图所示,但这需要将验证逻辑转换为JS。

如果您希望使用服务器端逻辑在客户端进行这些验证,则可以实现[Remote]属性,该属性允许您指定将被调用以验证属性的操作。您还可以指定将用于执行验证的其他属性。您可以在这里找到一些关于如何实现此选项的示例,包括其他属性。缺点是没有在服务器上强制执行此验证。

最新更新