Masood tav Masood tav - 3 months ago 13
ASP.NET (C#) Question

CustomValidator doesn't work correctly in asp.net

I created a custom validator for FileUpload for control photos size and format

protected void cvrFileUpload_ServerValidate(object source, ServerValidateEventArgs args)
{
if (rbtnSelectByFile.Checked)
{
if (fuplBrows.HasFile)
{
string fileType = Path.GetExtension(fuplBrows.PostedFile.FileName).ToLower().Trim();
if (fileType != ".jpg" && fileType != ".png" && fileType != ".bmp" && fileType != ".jpeg")
{

cvrFileUpload.ToolTip = "Only .jpg, .png, .bmp file formats are allowed";
args.IsValid = false;
ScriptManager.RegisterStartupScript(this, GetType(), "pagechange", "nextPage(); ", true);
}
else
{
if (fuplBrows.PostedFile.ContentLength > 102400)
{
cvrFileUpload.ToolTip = "حجم فایل باید کمتر از 100 کیلوبایت باشد";
args.IsValid = false;
ClientScript.RegisterStartupScript(GetType(), "pagechange", "nextPage(); ", true);
return;
}
else
{
args.IsValid = true;
}
}
}
}

}


And have a button for saving information in the database that must not work if customvalidator is invalid:

protected void btnRegist_Click(object sender, EventArgs e)
{

ResultManage oRm = new ResultManage();

RequestInfo oRi = form2oRi();

int id = oRm.saveResult(oRi);

if (id > 0)
{
Response.Redirect("~/RecordedResult.aspx");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "پیام سیستم", "alert('خطا در انجام عملیات');", true);
}

}


I want to not work my button function when custom validator is invalid. How do I do this?

Answer

I'd suggest you use the

Page.IsValid 

Property to check if all Validators are valid:

http://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(v=vs.110).aspx