public class FileUploadTypeValidator : CustomValidator
{
public FileUploadTypeValidator()
{
base.ErrorMessage = "pdf, doc, docx, xls, xlsx, and ppt files are allowed.";
base.Text = "*";
base.SetFocusOnError = true;
base.ToolTip = "pdf, doc, docx, xls, xlsx, and ppt files are allowed.";
base.ClientValidationFunction = "ClientValidateFileType";
this.FileTypes = "pdfPDFdocDOCdocxDOCXxlsXLSxlsxXLSXpptPPT";
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), this.ClientID + "ADDScript", GetScript(), true);
}
protected override bool OnServerValidate(string value)
{
//return base.OnServerValidate(value);
FileUpload fu = this.Parent.FindControl(this.ControlToValidate) as FileUpload;
if (fu != null && !string.IsNullOrEmpty(fu.FileName))
{
string ext = System.IO.Path.GetExtension(fu.FileName);
string[] fileTypes = this.FileTypes.Split('');
foreach (string item in fileTypes)
{
if (!ext.Equals( "." + item))
{
return true;
}
}
}
return false;
}
public string FileTypes { get; set; }
private string GetScript()
{
string script = string.Empty;
script = @"function ClientValidateFileType(source, arguments) {"
+ " var FilePath = arguments.Value;"
+ " var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();"
+ " var exten = new Array();"
+ " exten = \"" + this.FileTypes + "\";"
+ " var extens = exten.split(\"\");"
+ " var isValid = false;"
+ " for (var i = 0; i < extens.length; i++) {"
+ " if (extens[i] == Extension) {"
+ " isValid = true;"
+ " break;"
+ " }"
+ " }"
+ " arguments.IsValid = isValid;"
+ " }";
return script;
}
}
The above code snippet checks the type of the in both the client and server side. In order to use this custom validator, use the following markup:
AELCtl is the tagprefix of the custom validator. You can set the type of files you want to allow by using the FileTypes property. The above validator allows jpg, jpeg and GIF files
Hope this help!
No comments:
Post a Comment