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

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?
mmedi005Asked:
Who is Participating?
 
RejojohnyCommented:
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
 
RejojohnyCommented:
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
 
mmedi005Author Commented:
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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
RejojohnyCommented:
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
 
Bob LearnedCommented:
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
 
mmedi005Author Commented:
what event from the requiredfieldvalidtor can i use to change the labels style?
0
 
Bob LearnedCommented:
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
 
RejojohnyCommented:
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
 
mmedi005Author Commented:
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
 
RejojohnyCommented:
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
 
RejojohnyCommented:
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
 
Bob LearnedCommented:
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
 
mmedi005Author Commented:
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
 
mmedi005Author Commented:
       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
 
mmedi005Author Commented:
>>I did explain myself right, but any how, you will both get points from me.

I meant "did not explain"
0
 
Bob LearnedCommented:
That almost sounds like you don't have validation set up correctly, like not setting the ControlToValidate property on the validator.

Bob
0
 
mmedi005Author Commented:
its set....with out the code, it would setfocus or show its errortext.

all was set up
0
 
Bob LearnedCommented:
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
 
mmedi005Author Commented:
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
 
mmedi005Author Commented:
       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
 
RejojohnyCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.