Hi moepyag,
You need to make use of IFormFile property to validate a file upload.
Refer below sample.
Model
using System.ComponentModel.DataAnnotations;
public class FileModel
{
[Required(ErrorMessage = "Please select file.")]
[RegularExpression(@"([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$", ErrorMessage = "Only Image files allowed.")]
public IFormFile PostedFile { get; set; }
}
Controller
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(IFormFile postedFile)
{
if (ModelState.IsValid)
{
}
return View();
}
}
View
@model FileUpload_Validation_Core.Models.FileModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post" enctype="multipart/form-data">
<span>Select File:</span>
<input type="file" asp-for="PostedFile" name="PostedFile" accept=".png, .jpg, .gif" />
<br />
<span asp-validation-for="PostedFile" style="color:red"></span>
<hr />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
</body>
</html>
Screenshot