Geeks With Blogs
Pankaj Tahiliani

1. Create a CSS Class that allows you to highlight invalid inputs and display messages in a pretty way
input.error 
{
 background: #fed; border: 1px solid red;
}

2. Create validators.js. Here are the contents from that file:
ValidatorCommonOnSubmit = function()
{                   
    ClearValidatorCallouts();
    var result = SetValidatorCallouts();                                                                                          
    return result;
}

ValidatorValidate = function(val, validationGroup, event)
{
    val.isvalid = true;
    if ((typeof(val.enabled) == 'undefined' || val.enabled != false) && IsValidationGroupMatch(val, validationGroup))
    {
        if (typeof(val.evaluationfunction) == 'function')
        {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null && typeof(val.focusOnError) == 'string' && val.focusOnError == 't')
            {
                ValidatorSetFocus(val, event);
            }
    }

}

    ClearValidatorCallouts();
    SetValidatorCallouts();
    ValidatorUpdateDisplay(val);
}

SetValidatorCallouts = function()
{
    var i;
    var pageValid = true;                   
    for (i = 0; i < Page_Validators.length; i++)
    {        
        var inputControl = document.getElementById(Page_Validators[i].controltovalidate);              
        if (!Page_Validators[i].isvalid)
        {  
            if(pageValid)
                inputControl.focus();
            WebForm_AppendToClassName(inputControl, 'error');
            pageValid = false;                                                    
        }                       
    }                   

  return pageValid;
}

ClearValidatorCallouts = function()
{
    var i;                   
    var invalidConrols = [];
    for (i = 0; i < Page_Validators.length; i++)
    {        
        var inputControl = document.getElementById(Page_Validators[i].controltovalidate);              
        WebForm_RemoveClassName(inputControl, 'error');                                                 
    }                                       
}

function WebForm_RemoveClassName(element, className)
{
    var current = element.className;
    if (current)
    {
      if (current.substring(current.length - className.length - 1, current.length) == ' ' + className)
      {
        element.className = current.substring(0, current.length - className.length - 1);
        return;
      }
     
      if (current == className)
      {
        element.className = "";
        return;
      }
     
      var index = current.indexOf(' ' + className + ' ');
      if (index != -1)
      {
        /* BUG 1: index + 1 instead of index to include one space */
        element.className = current.substring(0, index + 1) + current.substring(index + className.length + 2, current.length);
        return;
      }
     
      /* BUG 2: className.length + 1 instead of className.length in order that the comparison is true */
      if (current.substring(0, className.length + 1) == className + ' ')
        element.className = current.substring(className.length + 1, current.length);
    }
}
function WebForm_AppendToClassName(element, className)
{
    var current = element.className;
    if (current)
    {
        if (current.charAt(current.length - 1) != ' ')
        {
            current += ' ';
        }
        current += className;
    }
    else
    {
        current = className;
    }
    element.className = current;
}

3. Override the Render event handler of your Page or MasterPage class to insert a reference to your re-written event validation scripts
Protected Sub form1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.PreRender
        Dim validatorOverrideScripts As String = "<script src='validators.js' type='text/javascript'></script>"
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "ValidatorOverrideScripts", validatorOverrideScripts, False)
        MyBase.OnPreRender(e)
End Sub

4. Lastly, Add some validators to a web form and see it in action
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>:: Trap Safari Enter Key ::</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>      
<fieldset>
<legend>Login Information</legend>
<div class="row">
<label class="required">
Email Address
<span class="subtle"></span>
</label>
<asp:TextBox ID="txtEmail1" CssClass="large required email"  runat="server" ></asp:TextBox>                           
<asp:RequiredFieldValidator ID="valEmail" runat="server" Display="Dynamic" ControlToValidate="txtEmail1" ErrorMessage="Email Address is required."><span class="error">Email Address is required.</span></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="valEmailAdd" runat="server" Display="Dynamic" ControlToValidate="txtEmail1" ValidationExpression=".*@.{2,}\..{2,}" ErrorMessage="Email Address should be in name@domain.com format."><span class="error">Email Address should be in name@domain.com format.</span></asp:RegularExpressionValidator>
<div class="clear"></div>
</div>
<div class="row">
<label class="required">Password</label>
<asp:Textbox ID="txtPassword" CssClass="large required" runat="server"  ></asp:Textbox>
<div class="clear"></div>
</div>
<div class="row">
<label class="required">Confirm Password</label>
<asp:TextBox ID="txtConPassword" CssClass="large required"  runat="server" ></asp:TextBox>
<div class="clear"></div>
</div>
</fieldset>
    </div>
    </form>
</body>
</html>

Note: Originally posted here: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=362. But I have made few modifications in that.

Posted on Thursday, August 13, 2009 12:38 AM | Back to top


Comments on this post: Highlighting TextBox on Error using Required Field Validator

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Works like a charm, thanks!
Left by Ariel Popovsky on Sep 10, 2009 9:45 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Thank you! Saved my skin
Left by Tyrone on Sep 14, 2009 2:16 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
This worked great, any idea how to display the errors in the validation summary dynamically as the css class is change as well? Basically, showing the errors in the summary instead.
Left by Ryan on Feb 12, 2010 11:21 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Great peice of code it save me typing it all out and checking / testing that it all works
Left by Gary Glitter on Aug 04, 2010 9:56 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Follow the instructions above but use this script along with jQuery to achieve the same thing.

OrginalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay =
function CustomValidatorUpdateDisplay(val) {
OrginalValidatorUpdateDisplay(val);
$('#' + val.controltovalidate).toggleClass('error', !val.isvalid);
}
Left by Nathan Papineau on Aug 23, 2010 1:01 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
works really cool but i am having problems while using it inside an update panel.

it looks like asp.net only renders the validation scripts when they are needed and if this comes to happen inside an update panel it is difficult (so far impossible for me) to override them correctly.

any clue ? anybody ?

thx!
Left by Jazz on Oct 19, 2010 3:00 PM

# With a bit of jQuery
Requesting Gravatar...
/* Form validation */

$(document).ready(function () {

var check = function ($ctrl) {
var isValid = true;
$.each(Page_Validators, function () { isValid = isValid && (this.ctv != $ctrl.attr('id') || this.isvalid); });
$ctrl.toggleClass('validationError', !isValid);
};

$.each(Page_Validators, function () {
$('#' + this.controltovalidate).unbind('change.pv').bind('change.pv', function () { check($(this)); });
check($('#' + this.controltovalidate));
});

});

/* END Form validation */
Left by chaos83 on Feb 22, 2011 9:27 PM

# With a bit of jQuery (with update panels)
Requesting Gravatar...
/* Form validation */

function formatValidationErrors() {
var check = function ($ctrl) {
var isValid = true;
$.each(Page_Validators, function () { isValid = isValid && (this.controltovalidate != $ctrl.attr('id') || this.isvalid); });
$ctrl.toggleClass('validationError', !isValid);
};

$.each(Page_Validators, function () {
$('#' + this.controltovalidate).unbind('change.pv').bind('change.pv', function () { check($(this)); });
check($('#' + this.controltovalidate));
});
}

$(document).ready(function () {
formatValidationErrors();
try { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(formatValidationErrors); } catch (e) { }
});

/* END Form validation */
Left by chaos83 on Feb 22, 2011 9:43 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Very helpful code.thanks
Left by Shweta on Mar 06, 2011 11:08 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
@chaos83:
What is change.pv in your code?
Left by stv on Mar 18, 2011 11:47 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Anyone have the full source for this working within Update Panel?

Also is the JQuery code to just go on the individual page or does that need to go in the js file as well?

Thanks
Left by cityBen on May 26, 2011 8:32 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Truly amazing. Exactly what I was looking for. The code is pretty self explainatory. Thanks for sharing!
Left by Sai Kodi on Jun 02, 2011 3:38 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Hi,
I tried adding this piece of code and my site is down at the point MyBase.OnPreRender(e). Any idea? please not this is being used in a Dotnetnuke site.
Left by Krishna on Sep 28, 2011 7:44 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
What about causes validation = false? The script doesn't seemt to account for this case, so once validation has happened, and the user clicks on a button that is causesvalidation="false", it doesn't work
Left by Paul on Apr 17, 2012 8:42 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Use the following replacement for ValidatorCommonOnSubmit instead, to respect causesvalidation settings:

ValidatorCommonOnSubmit = function () {
Page_InvalidControlToBeFocused = null;
var result = !Page_BlockSubmit;
if ((typeof (window.event) != "undefined") && (window.event != null)) {
window.event.returnValue = result;
}
Page_BlockSubmit = false;
ClearValidatorCallouts();
SetValidatorCallouts();
return result;
}
Left by Paul on Apr 17, 2012 9:05 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Nice solution, doesn't work for me in Mozilla Firefox though...
Left by Darina on Dec 19, 2012 8:44 AM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Blackberry phone read detail beneath AndroDumpper purposes just, i'm not responsible for any kind
Left by edward on Aug 01, 2017 4:52 PM

# mobdrotvguide
Requesting Gravatar...
Mobdro is one of the very best streaming sites where you can enjoy videos. mobdrotvguide Install the app successfully on your device.After the downloading and install.
Left by harry on Sep 26, 2017 3:08 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
Capture video clips for Instagram and also Vine. vivavideomaker enjoy to utilize this vivavideo application on their smartphones.
Left by Revin on Oct 06, 2017 3:11 PM

# re: Highlighting TextBox on Error using Required Field Validator
Requesting Gravatar...
In instance you are not able to motion a bağlantı after that be particular LiveNetTV the best application around to see your favored tv programs.
Left by grish on Dec 05, 2017 3:09 PM

Your comment:
 (will show your gravatar)


Copyright © Pankaj Tahiliani | Powered by: GeeksWithBlogs.net