据我所知,IValidatableObject它用于以一种方式验证对象,让人们相互比较属性.
我仍然希望有属性来验证单个属性,但我想在某些情况下忽略某些属性的失败.
我是否试图在下面的情况下错误地使用它?如果不是我如何实现这个?
public class ValidateMe : IValidatableObject
{
[Required]
public bool Enable { get; set; }
[Range(1, 5)]
public int Prop1 { get; set; }
[Range(1, 5)]
public int Prop2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!this.Enable)
{
/* Return valid result here.
* I don't care if Prop1 and Prop2 are out of range
* if the whole object is not "enabled"
*/
}
else
{
/* Check if Prop1 and Prop2 …Run Code Online (Sandbox Code Playgroud) 我想创建一个自定义验证属性,我想在其中将my属性的值与我的模型类中的另一个属性值进行比较.例如我在我的模型类中:
...
public string SourceCity { get; set; }
public string DestinationCity { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想创建一个自定义属性来像这样使用它:
[Custom("SourceCity", ErrorMessage = "the source and destination should not be equal")]
public string DestinationCity { get; set; }
//this wil lcompare SourceCity with DestinationCity
Run Code Online (Sandbox Code Playgroud)
我要怎么去那儿?
我正在使用 ASP.NET Core 2.2 并且我正在使用模型绑定来上传文件。
这是我的UserViewModel
public class UserViewModel
{
[Required(ErrorMessage = "Please select a file.")]
[DataType(DataType.Upload)]
public IFormFile Photo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的视图
@model UserViewModel
<form method="post"
asp-action="UploadPhoto"
asp-controller="TestFileUpload"
enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="Photo" />
<span asp-validation-for="Photo" class="text-danger"></span>
<input type="submit" value="Upload"/>
</form>
Run Code Online (Sandbox Code Playgroud)
最后这是MyController
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UploadPhoto(UserViewModel userViewModel)
{
if (ModelState.IsValid)
{
var formFile = userViewModel.Photo;
if (formFile == null || formFile.Length == 0)
{
ModelState.AddModelError("", "Uploaded file is empty or …Run Code Online (Sandbox Code Playgroud)