add custom attribute for file mime type validation #6

Manually merged
wanderer merged 6 commits from feature-custom-attr-validation into master 2021-01-26 15:24:09 +01:00
6 changed files with 31 additions and 5 deletions
Showing only changes of commit cf223daf81 - Show all commits

View File

@ -13,4 +13,5 @@
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script defer src="~/js/validation/file_type.js"></script>
}

View File

@ -13,4 +13,5 @@
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script defer src="~/js/validation/file_type.js"></script>
}

View File

@ -17,7 +17,7 @@
</div>
<div class="form-group">
<label asp-for="@Model.Image"></label>
<input asp-for="@Model.Image" accept="image/*" class="form-inline" id="inputCarousel" aria-describedby="the image">
<input id="file" asp-for="@Model.Image" accept="image/*" class="form-inline" id="inputCarousel" aria-describedby="the image">
<span asp-validation-for="@Model.Image" class="text-danger"></span>
</div>
<div class="form-group">

View File

@ -13,7 +13,6 @@ namespace pwt_0x01_ng.Models
[NotMapped]
[FileTypeAttr("image")]
public IFormFile Image { get; set; }
[Required]
[StringLength(255)]
public string ImageSrc { get; set; }
[Required]

View File

@ -28,12 +28,12 @@ namespace pwt_0x01_ng.Models.Validation
throw new NotImplementedException($"Attribute {nameof(FileTypeAttr)} not implemented for object {value.GetType()}.");
}
protected string GetErrorMessage(string member_name) => $"make sure your {member_name} really is an image ({type}).";
protected string GetErrorMessage(string member_name) => $"make sure the {member_name} you picked really is an image ({type}/*).";
public void AddValidation(ClientModelValidationContext ctx){
MergeAttribute(ctx.Attributes, "data-val", "true");
MergeAttribute(ctx.Attributes, "data-val-content", GetErrorMessage("File"));
MergeAttribute(ctx.Attributes, "data-val-filetype", type);
MergeAttribute(ctx.Attributes, "data-val-content", GetErrorMessage("file"));
MergeAttribute(ctx.Attributes, "data-val-content-type", type);
}
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value){

View File

@ -0,0 +1,25 @@
$.validator.addMethod('content', function (value, element, params) {
var f_type = params[1]
uploaded_type = "";
if (!value) {
return true;
}
if (element && element.files && element.files.length > 0) {
uploaded_type = element.files[0].type;
}
if (f_type && uploaded_type != "" && uploaded_type.toLowerCase().includes(f_type)) {
return true;
}
return false;
});
$.validator.unobtrusive.adapters.add('content', ['type'], function (options) {
var element = $(options.form).find('#file')[0];
options.rules['content'] = [element, options.params['type']];
options.messages['content'] = options.message;
});