dimanche 25 mai 2014

c# - validation du côté client personnalisé avec le téléchargement d'un fichier - Stack Overflow


I'm creating my own data annotation with client side validation to check if the chosen files are allowed, but i can't get it to work. The client side method doesn't get fired up.


I'm not getting any JavaScript errors.


Model:


public class FotoAlbumModel
{
public int AlbumId { get; set; }

[Filters.Required]
[MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 150 tekens.")]
public string Titel { get; set; }

[Filters.Required]
[MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 2500 tekens.")]
public string Descriptie { get; set; }

[Filters.Required]
[MaxLength(250, ErrorMessage = "Dit veld mag niet langer zijn dan 250 tekens.")]
public string Keywoorden { get; set; }

[Filters.Required]
[LinkName]
public string Linknaam { get; set; }

public bool Status { get; set; }

public int AantalFotos { get; set; }

[Filters.FileExtensions(FileExtensions = ".bmp,.jpg,.png.gif,.jpeg")]
public HttpPostedFileBase[] Fotos { get; set; }
}

My annotation:


public class FileExtensionsAttribute : ValidationAttribute, IClientValidatable
{
public string FileExtensions { get; set; }

public override bool IsValid(object value)
{
string strValue = value == null ? "" : value.ToString();

string[] arrayFileExtensions = FileExtensions.Split(',');

bool isMatch = arrayFileExtensions.Any(x => x.Contains(Path.GetExtension(strValue)));

if (!isMatch && ErrorMessage == null)
{
ErrorMessage = "De extensie van de bestand is niet toegestaan.";
}
return isMatch;
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = "De extensie van de bestand is niet toegestaan.",
ValidationType = "fileextension"

};
rule.ValidationParameters.Add("allowedextensions", FileExtensions);

yield return rule;
}
}

My custom validation adapter:


$.validator.unobtrusive.adapters.addSingleVal("fileextension", "allowedextensions");

$.validator.addMethod("fileextension", function (value, element, allowedextensions) {
alert('sds');
var arrayAllowedExtensions = allowedextensions.split(',');
var fileExtension = value.split('.').pop();
$.each(arrayAllowedExtensions, function(extension) {
if (extension == fileExtension) {
return true;
}
});
return false;
});

Html:


   @Html.TextBoxFor(m=> m.Fotos, new {@type="file", @multiple="true", @onchange="makeFileList();", @id="filesToUpload", @style="display: none;"})
<input type="button" value="Plaatje(s) selecteren" class="btn btn-green btn-gradient" onclick="document.getElementById('filesToUpload').click();" />
<ul id="fileList">
<li>No Files Selected</li>
</ul>
@Html.ValidationMessageFor(m => m.Fotos)

MakeFileList Javascript function:


<script>
function makeFileList() {
var input = document.getElementById("filesToUpload");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
}
</script>

Any ideas why the method is not being fired up?




I think this is because you're hiding the control that the FileExtensionsAttribute code is trying to validate.


Look at your page using Firebug, and you can see that the hidden control <input id="filesToUpload" type="file" has the validation data-val-fileextension="De extensie van de bestand is niet toegestaan."


If you modify your textbox @Html.TextBoxFor(m=> m.Fotos by removing the @style="display: none;" attribute, you'll see that your validation works.


Unfortunately I'm not sure how to get round this problem. Is there a reason you can't use the standard file upload control?




I am refering a link below which may help you !!!


Click here!



I'm creating my own data annotation with client side validation to check if the chosen files are allowed, but i can't get it to work. The client side method doesn't get fired up.


I'm not getting any JavaScript errors.


Model:


public class FotoAlbumModel
{
public int AlbumId { get; set; }

[Filters.Required]
[MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 150 tekens.")]
public string Titel { get; set; }

[Filters.Required]
[MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 2500 tekens.")]
public string Descriptie { get; set; }

[Filters.Required]
[MaxLength(250, ErrorMessage = "Dit veld mag niet langer zijn dan 250 tekens.")]
public string Keywoorden { get; set; }

[Filters.Required]
[LinkName]
public string Linknaam { get; set; }

public bool Status { get; set; }

public int AantalFotos { get; set; }

[Filters.FileExtensions(FileExtensions = ".bmp,.jpg,.png.gif,.jpeg")]
public HttpPostedFileBase[] Fotos { get; set; }
}

My annotation:


public class FileExtensionsAttribute : ValidationAttribute, IClientValidatable
{
public string FileExtensions { get; set; }

public override bool IsValid(object value)
{
string strValue = value == null ? "" : value.ToString();

string[] arrayFileExtensions = FileExtensions.Split(',');

bool isMatch = arrayFileExtensions.Any(x => x.Contains(Path.GetExtension(strValue)));

if (!isMatch && ErrorMessage == null)
{
ErrorMessage = "De extensie van de bestand is niet toegestaan.";
}
return isMatch;
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = "De extensie van de bestand is niet toegestaan.",
ValidationType = "fileextension"

};
rule.ValidationParameters.Add("allowedextensions", FileExtensions);

yield return rule;
}
}

My custom validation adapter:


$.validator.unobtrusive.adapters.addSingleVal("fileextension", "allowedextensions");

$.validator.addMethod("fileextension", function (value, element, allowedextensions) {
alert('sds');
var arrayAllowedExtensions = allowedextensions.split(',');
var fileExtension = value.split('.').pop();
$.each(arrayAllowedExtensions, function(extension) {
if (extension == fileExtension) {
return true;
}
});
return false;
});

Html:


   @Html.TextBoxFor(m=> m.Fotos, new {@type="file", @multiple="true", @onchange="makeFileList();", @id="filesToUpload", @style="display: none;"})
<input type="button" value="Plaatje(s) selecteren" class="btn btn-green btn-gradient" onclick="document.getElementById('filesToUpload').click();" />
<ul id="fileList">
<li>No Files Selected</li>
</ul>
@Html.ValidationMessageFor(m => m.Fotos)

MakeFileList Javascript function:


<script>
function makeFileList() {
var input = document.getElementById("filesToUpload");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
}
</script>

Any ideas why the method is not being fired up?



I think this is because you're hiding the control that the FileExtensionsAttribute code is trying to validate.


Look at your page using Firebug, and you can see that the hidden control <input id="filesToUpload" type="file" has the validation data-val-fileextension="De extensie van de bestand is niet toegestaan."


If you modify your textbox @Html.TextBoxFor(m=> m.Fotos by removing the @style="display: none;" attribute, you'll see that your validation works.


Unfortunately I'm not sure how to get round this problem. Is there a reason you can't use the standard file upload control?



I am refering a link below which may help you !!!


Click here!


0 commentaires:

Enregistrer un commentaire