ASP.NET - how to highlight textbox border by using required field validator

Asked By chaitanya a on 23-Nov-11 07:02 AM
here im using required field validator for checking user name is blank or not.i want to text box color should be red when ever  req.Field validator error message will come how to do that one
<asp:TextBox ID="txtPassWord" runat="server" SkinID="LoginFields" 
                             TextMode="Password" > </asp:TextBox>    


<asp:RequiredFieldValidator ID="rfvLoginPassword" runat="server" 
                                     ControlToValidate="txtPassWord" Display="Dynamic" 
                                     ErrorMessage="Password Can't be Blank" SetFocusOnError="True" Font-Names="Arial" Font-Size="12px"></asp:RequiredFieldValidator>


can any one help me plz
dipa ahuja replied to chaitanya a on 23-Nov-11 07:05 AM
Its requiredFieldValidator. means blank textBox, so how can you set its fore color for the blank textbox which doesn't have text??

It just display the error in red forecolor
chaitanya a replied to dipa ahuja on 23-Nov-11 07:07 AM
then how can i show that border as red when it is blank?
Chintan Vaghela replied to chaitanya a on 23-Nov-11 07:08 AM
Hello

Here is a way of changing back ground color for Textbox on validation failure. The key here is using Page_ClientValidate function in javascript.

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ErrorMessage=”Please enter a value”
ControlToValidate=”TextBox1″></asp:RequiredFieldValidator>
<asp:Button ID=”Button1″ runat=”server” Text=”Button” OnClientClick=”btnClick();”
OnClick=”Button1_Click1″ />

<script type=”text/javascript”>
function btnClick()
{
if (!Page_ClientValidate())
{
document.getElementById(“TextBox1″).style.backgroundColor=”red”;
}
}
function ClearBackGround()
{
document.getElementById(“TextBox1″).style.backgroundColor=”";
}
</script>

In Code behind


TextBox1.Attributes.Add(“onkeypress”, “ClearBackGround()”);

Hope this helpful
Suchit shah replied to chaitanya a on 23-Nov-11 07:09 AM
You can do that with a Custom Validator
  <asp:TextBox ID="TextBox1" runat="server" />
     
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="" />
     
<br />
     
<asp:TextBox ID="TextBox2" runat="server" />
     
<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="" />
     
<br />
     
<asp:Button ID="Button1" runat="server" Text="Button" />

------------------------
Code behind

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
     
If TextBox1.Text = String.Empty Then
       
TextBox1.Style.Add("border", "solid 1px red")
        args
.IsValid = False
     
Else
       
TextBox1.Style.Add("border", "solid 1px black")
        args
.IsValid = True 
     
End If
   
End Sub

   
Protected Sub CustomValidator2_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator2.ServerValidate
     
If TextBox2.Text = String.Empty Then
       
TextBox2.Style.Add("border", "solid 1px red")
        args
.IsValid = False
     
Else
       
TextBox2.Style.Add("border", "solid 1px black")
        args
.IsValid = True
     
End If
   
End
Sub
Suchit shah replied to chaitanya a on 23-Nov-11 07:09 AM
try this
  
<style type="text/css">
 .error {
  BORDER-RIGHT: red 2px solid;
BORDER-TOP: red 2px solid;
BORDER-LEFT: red 2px solid;
BORDER-BOTTOM: red 2px solid }
  
</style>
  
  
  
<html >
 <head id="Head1" runat="server">
 <title>Update</title>
    <script type="text/javascript">
    </script>
 </head>
 <body >
  <form id="form1" runat="server">  
 <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"
   ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
  <asp:ValidationSummary ID="ValidationSummary1" runat="server"
   ShowMessageBox="True" ShowSummary="false" /> 
   <script type="text/javascript">
      //<![CDATA[
      function WebForm_OnSubmit() {
        if (typeof (ValidatorOnSubmit) =="function" && ValidatorOnSubmit() == false) {
          document.getElementById("<%=txtName.ClientID%>").className ="error";
          return false;
        }
        else {
          return true;
        }
      }
      //]]>
 </script>
  <asp:Button ID="Button1" runat="server" Text="Button" />
   </form>
 </body>
 </html>
chaitanya a replied to Suchit shah on 23-Nov-11 07:18 AM
I tried that code what u send still it is showing only error message,the border color is nt changing 
dipa ahuja replied to chaitanya a on 23-Nov-11 07:20 AM
You can use javascript function for that:

  <script type="text/javascript">
    function check(pw) {
      pw.style.borderColor = (pw.value == "") ? "Red" : pw.style.BorderColor = "";
    }
  </script>
 <asp:TextBox ID="txtPassWord" runat="server" SkinID="LoginFields" onblur="check(this)"
    TextMode="Password"> </asp:TextBox>
chaitanya a replied to dipa ahuja on 23-Nov-11 07:25 AM
when i click on submit button only i have display error message and then change that text box border to red color.not on onblur() event
chaitanya a replied to Chintan Vaghela on 23-Nov-11 07:27 AM
when i execute the above code only error message is displaying .Bt border color is not changing wat to do
dipa ahuja replied to chaitanya a on 23-Nov-11 07:29 AM
<script type="text/javascript">
    function check() {
      var pw = document.getElementById('<%= txtPassWord.ClientID %>');
      pw.style.borderColor = (pw.value == "") ? "Red" : pw.style.BorderColor = "";
    }
  </script>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" OnClientClick="check()" />
chaitanya a replied to dipa ahuja on 23-Nov-11 07:34 AM
still the color is nt changing
dipa ahuja replied to chaitanya a on 23-Nov-11 07:35 AM
It is being changed.. i have tested and then posted.. check your code once again..
chaitanya a replied to dipa ahuja on 23-Nov-11 07:42 AM
sry i use the same code wat u send bt still it is nt cmg
.error  
 {
     border-bottom:solid 1px red;
     border-left:solid 1px red;
     border-right:solid 1px red;
     border-top:solid 1px red;  
  
 }
  
</style>
<script type="text/javascript">
    function check() {
        alert("hh");
        var pw = document.getElementById("txtPassWord");
        pw.style.borderColor = (pw.value == "") ? "Red" : pw.style.BorderColor = "";
    }
 </script>
<asp:TextBox ID="txtPassWord" runat="server" SkinID="LoginFields" 
                             TextMode="Password" > </asp:TextBox>   
 <asp:Button ID="btnSubmit" runat="server" SkinID="LoginSubmit" Text="Submit" 
                              OnClientClick="javascript:check()"></asp:Button > 
plz check


Suchit shah replied to chaitanya a on 23-Nov-11 07:47 AM
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>



Refrence from the :http://geekswithblogs.net/ptahiliani/archive/2009/08/13/highlighting-textbox-on-error-using-required-field-validator.aspx
dipa ahuja replied to chaitanya a on 23-Nov-11 07:48 AM
there is no need of css..

remove the .error css class

this code is working properly at my side

Chintan Vaghela replied to chaitanya a on 23-Nov-11 07:58 AM
HEllo

Change your javascript as follows


function btnClick() {

        if (typeof (Page_ClientValidate) == 'function')

          Page_ClientValidate();

        if (!Page_ClientValidate()) {

          document.getElementById("txtName").style.borderColor  = "red";

          return false;

        }

        return true;

      }

      function ClearBackGround() {

        document.getElementById("txtName").style.borderColor = "";

      }

 

Aspx page as follows


<asp:TextBox ID="txtName" ValidationGroup="A" runat="server"></asp:TextBox>

    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please

      enter a value" ValidationGroup="A" ControlToValidate="txtName"></asp:RequiredFieldValidator>

    <asp:Button ID="btnAdd" runat="server" ValidationGroup="A" Text="Button" OnClientClick="return btnClick()" />


.cs page Load as follows

txtName.Attributes.Add("onkeypress", "ClearBackGround()");



Hope this helpful

check it let me know your feedback
chaitanya a replied to Chintan Vaghela on 23-Nov-11 08:06 AM
sry still same issue only error message is coming bt border color is nt changing it shows border color as yellow
Chintan Vaghela replied to chaitanya a on 23-Nov-11 08:23 AM
can you send me your code?
chaitanya a replied to Chintan Vaghela on 23-Nov-11 10:58 PM
Hi This is my code

<script type="text/javascript">
    function btnClick() {
        if (typeof (Page_ClientValidate) == 'function')
            Page_ClientValidate();
        if (!Page_ClientValidate()) {
            document.getElementById("txtUserName").style.borderColor = "red";
            return false;
        }
        return true;
    }
    function ClearBackGround() {
        document.getElementById("txtUserName").style.borderColor = "";
    }
 </script>


and  <asp:TextBox ID="txtUserName" runat="server" SkinID="LoginFields" ValidationGroup="A" > </asp:TextBox>
asp:RequiredFieldValidator ID="rfvLoginUsername" runat="server" 
                                     ControlToValidate="txtUserName" Display="Dynamic"  ValidationGroup="A" 
                                     ErrorMessage="Usename Can't be Blank" SetFocusOnError="True" Font-Names="Arial" Font-Size="12px" BorderColor="Red"></asp:RequiredFieldValidator>
This is my code     


chaitanya a replied to Chintan Vaghela on 23-Nov-11 11:32 PM
 i send my code 
 can u plz help me
Chintan Vaghela replied to chaitanya a on 24-Nov-11 12:00 AM

Hello

 

Added javascript function on textbox onchange event

    <asp:TextBox ID="txtName" onchange="return btnClick()" ValidationGroup="A" runat="server"></asp:TextBox>

 

<script type="text/javascript">

 

      function btnClick() {

        var test;

        if (typeof (Page_ClientValidate) == 'function')

          test = Page_ClientValidate();

        if (!test) {

          document.getElementById("txtName").style.borderColor = "red";

          return false;

        }

        return true;

      }

 

    </script>

chaitanya a replied to Chintan Vaghela on 24-Nov-11 12:24 AM
If i copy that code in another page and when i excute that one it is wrkng fine.Bt here it is not wrking
Chintan Vaghela replied to chaitanya a on 24-Nov-11 12:41 AM
Hello


Remove SkinID="LoginFields"  from textbox

and let me know

chaitanya a replied to Chintan Vaghela on 24-Nov-11 12:45 AM
Thanks A lot now it is wrkng fine :)
Chintan Vaghela replied to chaitanya a on 24-Nov-11 12:48 AM
You most welcome in eggheadcafe