|
|||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Describing the problemIn a project I am working in, I was faced with a problem. The client asked to change the default presentation of the errors that appeared. He wanted to highlight a background of the field with a custom color when a user entered wrong data on a form. The ordinary technique to show that the validation process failed is to show some red text in a certain position, or just an asterisk. In addition to this, we can also place a
In this article, I am going to show how to add a special Cascading Style Sheet class name to an attached control in an error situation, on the server and the client sides, or even call a custom client function. In addition, I am going to show how to customize validation summary results. You can download the sources (10.9 Kb), and easily add the functionalities to your form. There is a class library called How to use the solutionTo use it, you need to go through these steps:
Diving in to the codeTo enhance the standard validators, I used them as inherited classes, and created a new branch of validators with the “Highlight” prefix, because I just wanted to add some desired functionality and maintain compatibility so developers can easily switch between the standard ASP.NET validators and the enhanced Highlight validators. At first, let’s take a look at how changing the class name works. There are two parts of the code – server and client sides. With the server side, everything is easy: I just added a check whether the validator is valid or if the validation process failed. If it isn’t valid, I add an error class name to the attached control: protected override void OnPreRender(EventArgs e)
{
WebControl control = (WebControl)Parent.FindControl(ControlToValidate);
ClassNameHelper.Remove(control, this.errorCssClass);
if (!IsValid)
{
ClassNameHelper.Add(control, this.errorCssClass);
}
base.OnPreRender(e);
}
The Nothing interesting so far. But let’s figure out how to change the class name of the attached control on the client side before the user postbacks the form. As I said in the introduction section, if we set I found there, the function ValidatorUpdateDisplay(val) {
if (typeof(val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
That’s it! Client scripts use it to show/hide the red error message of the validator. So if we can override it, we can add some additional code, and that will help to implement the enhanced functionalities. To achieve this, I used a little trick – a hijacking. For example, if we have a function var oldTest;
function newTest()
{
// call oldTest function
oldTest();
// execute some additional code
alert("we've overrided it");
}
window.onload = function()
{
// hijack test() method
oldTest = test;
test = newTest;
}
When the page loads ( Let’s go back to the
Now, I am going to override the private string errorCssClass;
public string ErrorCssClass
{
get { return this.errorCssClass; }
set { this.errorCssClass = value; }
}
private string errorClientFunction;
public string ErrorClientFunction
{
get { return this.errorClientFunction; }
set { this.errorClientFunction = value; }
}
protected override void OnLoad(EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
...
Control control = Parent.FindControl(this.ControlToValidate);
if (control != null)
{
if (!cs.IsClientScriptBlockRegistered(this.GetType(),
String.Format("HighlightValidation_{0}", this.ClientID)))
{
cs.RegisterClientScriptBlock(this.GetType(),
String.Format("HighlightValidation_{0}", this.ClientID),
String.Format("Page_HighlightValidators.push(
new Array('{0}', '{1}', '{2}', '{3}'));",
this.ClientID, control.ClientID, this.errorCssClass,
this.errorClientFunction), true);
}
}
...
}
I use the Eventually, I can use a loop in an already overridden function newValidatorUpdateDisplay(val)
{
// call hijacked ValidatorUpdateDisplay() method
oldValidatorUpdateDisplay(val);
for (i = 0; i < Page_HighlightValidators.length; i++)
{
if (val.id == Page_HighlightValidators[i][0] &&
val.controltovalidate == Page_HighlightValidators[i][1])
{
var control = document.getElementById(Page_HighlightValidators[i][1]);
var errorClassName = Page_HighlightValidators[i][2];
var errorCallFunction = Page_HighlightValidators[i][3];
// add class and change tooltip
if (errorClassName != "")
{
RemoveClassName(control, errorClassName);
if (!val.isvalid)
{
AddClassName(control, errorClassName);
control.title = val.attributes.title.value;
}
}
// call custom function
if (errorCallFunction != "" &&
eval("typeof("+errorCallFunction+")") == "function")
{
if (!val.isvalid)
{
eval(errorCallFunction+"(val)");
}
}
}
}
}
Instead of just replacing the class name with the error class name, I use the <div class="class_one class_two">...</div>
Please note also that the properties from the In the code above, I also added calling the custom error client function, and pass the Custom validation summary on the client sideNow, we've enhanced the validators, and can indicate to the customer who uses our form the kind of errors that happen, in any way we like, using custom error class names and custom client functions. But let's take a look at the For example, I want to place a Next, I am going to create a <div id="SummaryValidation">
<span>
<p style="font-weight:bold">The following errors were occured:</p>
<ul id="ValidationProblems"></ul>
</span>
</div>
I already added a header and a list tag, where I am planning to display all the errors. To center the In the next step, we need to attach the JavaScript function to the Submit event of the form, where we will check all the validators and create a list of errors if they are present; in the other case, we just let the form be posted to the server: protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsOnSubmitStatementRegistered(this.GetType(),
"PrepareValidationSummary"))
{
cs.RegisterOnSubmitStatement(this.GetType(),
"PrepareValidationSummary", "CheckForm()");
}
}
Now, I declare the function CheckForm()
{
if (!Page_IsValid)
{
var s = "";
for (i=0; i<Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid &&
typeof(Page_Validators[i].errormessage) == "string") {
s += "<li>" + Page_Validators[i].errormessage + "</li>";
}
}
if (s != "")
{
document.getElementById('ValidationProblems').innerHTML = s;
document.getElementById('SummaryValidation').style.display = 'inline';
}
}
}
In To hide the validation summary, create the I hope it is helpful to you, and will appreciate if you leave your opinions, corrections, or any other thoughts. Thanks for your time. Change history
| ||||||||||||||||||||||||||||