?
Solved

When a validator control is flagged, can I change the color of a label to red instead of having a message pop out?

Posted on 2007-10-17
21
Medium Priority
?
388 Views
Last Modified: 2013-11-07
When a validator control is flagged, can I change the color of a label to red instead of having a message pop out?

e.g. If the web page has a label First Name and a text box with a requiredfield validtor control for it.  The user submits a blank field, how can I change the label color to red instaed of a message popping up?
0
Comment
Question by:mmedi005
  • 9
  • 7
  • 5
21 Comments
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20094903
I had a similar requirement and I had to build a custom validator controls inherited from the standard ones .. i exposed a property called "LabelToHighlight" and this is set during design time .. in your case this will be "First Name" ..

then i registered a clientscript using RegisterClientScriptBlock (javascript function) which loops through the Page_Validators array (available when validators are placed in a aspx page)
I registered another function using RegisterOnSubmitStatement which calls the above javascript function on submit ..

After that its just a matter of drag and drop the custom validator and setting the "LabelTohighlight" property .. the other properties like controlToValidate, errormessage etc are still available and the page consuming the control is free to set it as needed ..

Rejo
0
 

Author Comment

by:mmedi005
ID: 20094948
Reason why I want this is because if I set 2 different validators next to each other, the second validtor displays its message with a space to the left, where i want it to align all the way to the left.  It's almost like the controlis there, but hidden, and when flagged its display is changed to true.  

Do you think javascript is the only way to go?

Would I be able to get an exmple to start me off in the right direction?
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20095080
you can set the "display" property of the validator contros to "dynamic" .. default is "static" .. if made "dynamic", the space is only occupied if there is a error .. else no space is taken in the page by the validator control ..

Rejo
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 20095505
This is pretty easy if you just set the style for a Label, and then set the Visible property when you need to show or hide the message.

Bob
0
 

Author Comment

by:mmedi005
ID: 20095632
what event from the requiredfieldvalidtor can i use to change the labels style?
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20095703
Here are examples from the Page_Load event:

C#
        if (!this.IsValid && this.RequiredFieldValidator1.IsValid)
            this.Label1.CssClass = "Error";
       else
            this.Label1.CssClass = "Valid";

VB.NET:
        If Not Me.IsValid AndAlso Me.RequiredFieldValidator1.IsValid Then
            Me.Label1.CssClass = "Error"
        Else
            Me.Label1.CssClass = "Valid"
        End If

Bob
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20095845
The reason why I did not do that is because changing the style needs to be set at the server .. or even if done at the client .. you will need to call the function for each of the error .. I do the same thing using a control .. the style of the label is changed on the client in the extended control .. but there is no code involved for each page, no function to be called, but just set a property ..

mmedi005, did the display property not work for you?
0
 

Author Comment

by:mmedi005
ID: 20095872
Yes the dynamic property worked, but Bob's suggestion was the direction i was going.  I don't mind if the validation event  is called on postback.  

But using Bob's method I got...

Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.

Any ideas?


0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20095940
The code that Bob gave needs to be within the event that caused the postback .. maybe a button click .. I think you might have added that code in page load event ...

I am surprised that you do not mind the postback just to highlight the error .. this kind off negates the usage of validator controls, esp where in a web application scenario where we try to acheive the maximum possible on the browser before we process it on the server .. anyway, you might have your own reason for taking that approach ..

Rejo
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20095950
by the way, I thoguht the reason why you are doing this is because "if I set 2 different validators next to each other, the second validtor displays its message with a space to the left, where i want it to align all the way to the left. " if the dynamic property worked, then where you not satisfied with the result? just curious ..

Rejo
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 800 total points
ID: 20095955
Sorry, got going a little too fast:

   if (this.IsPostBack)
   {
       if (!this.IsValid && this.RequiredFieldValidator1.IsValid)
            this.Label1.CssClass = "Error";
       else
            this.Label1.CssClass = "Valid";
   }

Bob
0
 

Author Comment

by:mmedi005
ID: 20095976
You are going to get points, you helped me a lot and I am very thankful.  Different ideas were thrown at me and I am trying the different suggestions.  Your responses were very good, and maybe my question went the a different direction or I did explain myself right, but any how, you will both get points from me.

Thank you again.  I still would like see an example of your first response.

thank you for all your help.

0
 

Author Comment

by:mmedi005
ID: 20095992
       If Me.IsPostBack Then

            If Not Me.IsValid AndAlso Me.rfv_RequiredFieldValidator1.IsValid Then
                Me.Label1.ForeColor = Drawing.Color.Red
            Else
                Me.Label1.ForeColor = Drawing.Color.Black
            End If

        End If

is what i put and still got the error...
0
 

Author Comment

by:mmedi005
ID: 20095995
>>I did explain myself right, but any how, you will both get points from me.

I meant "did not explain"
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20096028
That almost sounds like you don't have validation set up correctly, like not setting the ControlToValidate property on the validator.

Bob
0
 

Author Comment

by:mmedi005
ID: 20096036
its set....with out the code, it would setfocus or show its errortext.

all was set up
0
 
LVL 26

Accepted Solution

by:
Rejojohny earned 1200 total points
ID: 20096086
don't worry about the points :-) .. its like a bonus .. I also like to help (i.e if I can ..)

did you try adding that code within the click event which is causing the postback?

This is the code for the MyRequiredValidator ..

'Created by Rejo on Aug 23rd 2007
' Standard field validators has just the controltovalidate property which can be set to specify which
' controls needs to be validated. But the project requires the errors to highlight the label
' of the control which is been validated.
' This custom validator does just that.
' A new property added gives option to the developer to select a control which gets highlighted with a different style.
'   The styles are set as embeded resource and should be changed as per the requirement of the project
'   The styles too could have been exposed as public properties, but that would be each control will have to manually
'   set by the developer.
'   The javascript which changes the style is also embeded into the project
'   ONLY THE DLL NEEDS TO BE REFERENCED IN THE MAIN PROJECT which will consume these controls

Imports Microsoft.VisualBasic
Imports System.Web.UI
Imports System.ComponentModel
Imports System.Web.UI.WebControls

Namespace Controls

    <DefaultProperty("LabelToHighlight")> _
    Public Class CustomRequiredValidator
        Inherits System.Web.UI.WebControls.RequiredFieldValidator
        Dim lstrLabelToHighlight As String

        <Bindable(False), Category("Behavior"), Browsable(True), _
        DescriptionAttribute("The label that would be highlighted when there is an error."), _
        TypeConverter(GetType(ControlIDConverter))> _
        Public Property LabelToHighlight() As String
            'property to hold the name of the label control which would be highlighted when the error occurs
            Get
                Return lstrLabelToHighlight
            End Get
            Set(ByVal value As String)
                lstrLabelToHighlight = value
            End Set
        End Property

        'Protected Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter)
        '    'set the display property to none
        '    Me.Display = ValidatorDisplay.None
        '    MyBase.AddAttributesToRender(writer)
        '    If Not Me.LabelToHighlight Is Nothing Then
        '        'add the custom properties
        '        'writer.AddAttribute("LabelToHighlight", me.FindControl(  
        '        If Not Page.FindControl(Me.Parent.ClientID & "_" & Me.LabelToHighlight) Is Nothing Then
        '            writer.AddAttribute("LabelToHighlight", Page.FindControl(Me.LabelToHighlight).ClientID)
        '        End If
        '    End If
        'End Sub

        Private Sub CustomRequiredValidator_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            If Me.LabelToHighlight Is Nothing Then
                Throw New Exception("LabelToHighlight property is not set")
            End If
            'custom attribute is set here and not in addattributesToRender to
            '   take care of situation when the control is placed inside a parent control eg, user controls
            Me.Attributes.Add("LabelToHighlight", Me.FindControl(Me.LabelToHighlight).ClientID)

            'set the display property to none
            Me.Display = ValidatorDisplay.None

            'check if the script is already present and if not, then add it
            If Not Me.Page.ClientScript.IsClientScriptIncludeRegistered("ControlsCommon.js") Then
                Dim lstrScriptLocation As String = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "Delivery.ControlsCommon.js")
                Page.ClientScript.RegisterClientScriptInclude("ControlsCommon.js", lstrScriptLocation)

                ' add the style .. assumming that the style too would be added only once along with the js file
                Dim lstrTemplate As String = "<link rel='stylesheet' text='text/css' href='{0}' />"
                Dim lstrLocation As String = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "Delivery.ControlStyle.css")
                Dim lobjIncludeLiteral As LiteralControl = New LiteralControl(String.Format(lstrTemplate, lstrLocation))
                CType(Page.Header, HtmlControls.HtmlHead).Controls.Add(lobjIncludeLiteral)

                'register submit script which will call the script which will highlight the control if there is a error
                Me.Page.ClientScript.RegisterOnSubmitStatement(Me.GetType(), "HighlightLabelSubmit", "UpdateErrorLabel();")
            End If
        End Sub
    End Class
End Namespace

I did this in like a hour or so when my developers were not able to come up with a solution .. tried mutiple options and finally this seemed to work for me.. so wrote the code and shipped it to my developers and they have been using it in the project .. I am not updated whether they made any change to the code or not ... see if it works for you ..

note, the styles and the js file are embedded in the project and it is as given below
.js
function UpdateErrorLabel()
{
    var lobjValidator;

    //first reset all the existing validators to default style
    for (i = 0; i < Page_Validators.length; i++)
    {
            lobjValidator = document.getElementById(document.getElementById(Page_Validators[i].id).getAttribute('LabelToHighlight'));
            if (lobjValidator != null)
            {
                lobjValidator.className = 'lblnormal';
            }
     }
     
     //change the style for all error labels
    for (i = 0; i < Page_Validators.length; i++)
    {
        if (!Page_Validators[i].isvalid)
        {
            //lobjValidator = document.getElementById(Page_Validators[i].LabelToHighlight);
            lobjValidator = document.getElementById(document.getElementById(Page_Validators[i].id).getAttribute('LabelToHighlight'));
            if (lobjValidator != null)
            {
                //lobjValidator.setAttribute('class', 'lblerror');
                //lobjValidator.setAttribute('className', 'lblerror');
                lobjValidator.className = 'lblerror';
            }
        }
     }
}

style.css
.lblerror{background-color:Red; color:White; font-size:12px; font-family: 'Trebuchet MS';}
.lblnormal{background-color:White; color:Black; font-size:12px;font-family: 'Trebuchet MS';}
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20096097
I am being brain-dead today, so I am going to sit back, and clear my head before I say any more--OK?

Bob
0
 

Author Comment

by:mmedi005
ID: 20097242
I have some work to do, but im gonna try to make this work tonight.  thanks for all the help...ill be back posting early tomorrow.  My brain is also getting fried up.
0
 

Author Comment

by:mmedi005
ID: 20097295
       If Not Me.IsValid AndAlso Not Me.rfv_firstname.IsValid Then
            Me.lbl_first_name.ForeColor = Drawing.Color.Red
        Else
            Me.lbl_first_name.ForeColor = Drawing.Color.Black
        End If

worked in the click event. Also there was a NOT missing from the if statement.

 im gonna try the code later tonight when i'm done with some stuff around the office.

thanks again
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20097491
good .. as i said before .. you do not seem to be noticing my comments ;-) .. it will not work in page load as there is nothing to be validated and if you look the error message, that is what it says "It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate"

anyway, try the other code for the control and tell me if it works ..

Rejo
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Screencast - Getting to Know the Pipeline
Suggested Courses
Course of the Month16 days, 19 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question