Category Archives: ValidationSummary

[RESOLVED] changing backcolor of textbox when input is invalid......

Hello I have an ASP.net page with two textboxes where the user types in input.  I applied a requiredfieldvalidator to both textboxes as well.  However, I also want the textboxes to change to a backcolor of red if the form is invalid when the user clicks the button to submit the input.  I tried this code below in tthe button click event, but doesnt work...


If Page.IsValid = False Then
            txtCosts.BackColor = Drawing.Color.Red
            txtRevenue.BackColor = Drawing.Color.Red
        End If

How else can I change the Backcolor of the textboxes when the input is invalid.......

hi bababooey check this link here i explain clearly how to change the textbox background colorwhenever validation fails using asp.net

http://aspdotnet-suresh.blogspot.com/2011/01/how-to-change-textbox-background-color.html

You can do such validations client side.

Ofcourse the page needs to validated on the server too.

Here's an example  

//aspx
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script language="javascript" type="text/javascript">
        function abc(){
            if (typeof (Page_ClientValidate) == 'function') {
            Page_ClientValidate();
            }
            ChangeBackColor();
            if (!Page_IsValid) {
                return false;
            }
            return true;
        }


        function ChangeBackColor() {
            for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);
            if (ctrl != null && ctrl.style != null) {
                if (!CheckIfValid(ctrl)) {
                    ctrl.style.background = 'red';
            }
            else {
                ctrl.style.background = '';
            }
            ValidatorUpdateIsValid();
            ValidationSummaryOnSubmit(val.validationGroup);
        }


        function CheckIfValid(control) {
            for (var i = 0; i < control.Validators.length; i++) {
                if (!control.Validators[i].isvalid) {
                    return false;
                }
            }
            return true;
        }
    }
}
    </script>
    <div>
      <asp:TextBox ID="TextBox1" runat="server"  ></asp:TextBox>
      <asp:RequiredFieldValidator ID="Req1" runat="server" ErrorMessage="Required" Display="Dynamic"  ControlToValidate="TextBox1" ForeColor="Red"  Text="text1 Required" ValidationGroup="VGrp1"></asp:RequiredFieldValidator>
      <br />
      <asp:Button ID="btnsubmit"  runat="server" Text="Submit" OnClientClick="abc();"  onclick="btnsubmit_Click"/>
    </div>
    </form>


//codebehind
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("VGrp1");
        if (!Page.IsValid)
        {
            return;
        }
    }


 

If you are interested learning more on client side validation

http://simpledotnetsolutions.wordpress.com/2011/02/06/the-nuts-bolts-of-client-side-validation/

[RESOLVED] validator error message

I am having an issue with the "<br>" displaying in the error message of the validator. this is coming from a sql procedure so I have tried replace it with \n,\r\n, /\n/ and none of these have worked. What is the special character to create a new line in the error message for the validator.

griff303

I am having an issue with the "<br>" displaying in the error message of the validator. this

I tried <br> in Validtor error message, which seems to be working fine..

RequiredFieldValidator1.ErrorMessage = "Required Field <br>Required Field  <br> Required Field  ";

Did you try this with a validation summary? 

Hi,

The Validation Summary is same as RequiredFieldValidator.

  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ></asp:RequiredFieldValidator>
        <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

 

protected void Page_Load(object sender, EventArgs e)
        {
            this.RequiredFieldValidator1.ErrorMessage = "Required Field <br />Required Field <br /> Required Field";

            Response.Write("Hello, <br /> World!");
        }

 

Hope this can help you.

[RESOLVED] control validation appears in disorder

I

I´m using different validation controls from asp.net in a page that has like 10 controls.  When I click on insert validation occurs but my problem is that error messages appear in summary for some and other validation only takes place when I correct the first errors which is very confusing.  I´m trying to get all validation messages to be shown all at once but for some reason not all of them happen at the same time.

 

<InsertItemTemplate>
                        <table>
                            <tr>
                                <td>
                                    <asp:Label ID="lblContrato" runat="server" Text="Contrato"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewContrato" runat="server" Text='<%# Bind("contnume") %>'></asp:TextBox>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNewContrato"
                                        ErrorMessage="Contrato debe ser un numero" ValidationExpression="\d+">*</asp:RegularExpressionValidator>
                                    <ajaxToolkit:ValidatorCalloutExtender ID="RegularExpressionValidator1_ValidatorCalloutExtender"
                                        runat="server" Enabled="True" TargetControlID="RegularExpressionValidator1">
                                    </ajaxToolkit:ValidatorCalloutExtender>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                        ControlToValidate="txtNewContrato" ErrorMessage="Contrato es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblPersona" runat="server" Text="Persona"></asp:Label>
                                </td>
                                <td>
                         <%--<asp:DropDownList ID="DdPersona" runat="server" DataSourceID="OdsPersona"
                            DataTextField="nomCompleto" DataValueField="persnume"
                            SelectedValue='<%# Bind("persnume") %>' Font-Size="Small">
                        </asp:DropDownList>--%>
                         <%--<ajaxToolkit:DropDownExtender ID="DdPersona_DropDownExtender" runat="server"
                             DynamicServicePath="" Enabled="True" TargetControlID="DdPersona">
                         </ajaxToolkit:DropDownExtender>--%>
                        <asp:ObjectDataSource ID="OdsPersona" runat="server" SelectMethod="GetPersonaWithID"
                            TypeName="Facturacion.DAL.PersonaDataLayer" >
                            <SelectParameters>
                            <asp:Parameter DefaultValue="6" Name="tipenume" Type="Int16" />
                             </SelectParameters>
                            </asp:ObjectDataSource>
                            <ajaxToolkit:ComboBox ID="cmbPersona" runat="server"
                             AutoCompleteMode="Suggest" DataSourceID="OdsPersona"
                             DataTextField="nomCompleto" DataValueField="persnume" Text='<%# Bind("persnume") %>'
                             DropDownStyle="DropDownList" MaxLength="0" style="display: inline;"
                             AppendDataBoundItems="True" TabIndex="1">
                                <asp:ListItem Selected="True" Value="0">Seleccione persona</asp:ListItem>
                         </ajaxToolkit:ComboBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
                                        ControlToValidate="cmbPersona" ErrorMessage="Persona es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                            </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblFechaRegistro" runat="server" Text="Fecha de Registro"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewFechaRegistro" runat="server" Text="<%# System.DateTime.Now.ToString() %>"
                                        ReadOnly="True" TabIndex="8"></asp:TextBox>
                                </td>
                                <td>
                                    <asp:Label ID="lblFechaLegalizacion" runat="server" Text="Fecha de Legalizacion"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewFechaLegalizaion" runat="server"
                                        Text='<%# Bind("contfele") %>' TabIndex="2"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                                        ControlToValidate="txtNewFechaLegalizaion"
                                        ErrorMessage="Fecha de Legalizacion es requerido">*</asp:RequiredFieldValidator>
                                    <ajaxToolkit:CalendarExtender ID="txtNewFechaRegistro_CalendarExtender" runat="server"
                                        Enabled="True" TargetControlID="txtNewFechaLegalizaion" Format="dd/MM/yyyy" TodaysDateFormat="dd/MM/yyyy">
                                    </ajaxToolkit:CalendarExtender>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                                        ControlToValidate="txtNewFechaLegalizaion"
                                        ErrorMessage="Error en formato de fecha dd-mm-yyyy"
                                        ValidationExpression="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$"></asp:RegularExpressionValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblVendedor" runat="server" Text="Vendedor"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlVendedor" runat="server" DataSourceID="OdsVendedor" DataTextField="nomVendedor"
                                        DataValueField="vendnume" SelectedValue='<%# Bind("vendnume") %>' Font-Size="Small"
                                        AppendDataBoundItems="True" TabIndex="12">
                                        <asp:ListItem Selected="True" Value="0">Seleccione Vendedor</asp:ListItem>
                                    </asp:DropDownList>
                                    <asp:ObjectDataSource ID="odsVendedor" runat="server" SelectMethod="GetVendedores"
                                        TypeName="Facturacion.DAL.VendedorDataLayer"></asp:ObjectDataSource>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
                                        ControlToValidate="ddlVendedor" ErrorMessage="Vendedor es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblPrograma" runat="server" Text="Programa"></asp:Label>
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlPrograma" runat="server" DataSourceID="odsPrograma" DataTextField="prognomb"
                                        DataValueField="prognume" SelectedValue='<%# Bind("prognume") %>' Font-Size="Small"
                                        AppendDataBoundItems="True">
                                        <asp:ListItem Selected="0">Seleccione Programa</asp:ListItem>
                                    </asp:DropDownList>
                                    <asp:ObjectDataSource ID="odsPrograma" runat="server" SelectMethod="GetProgramas"
                                        TypeName="Facturacion.DAL.ProgramaDataLayer"></asp:ObjectDataSource>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
                                        ControlToValidate="ddlPrograma" ErrorMessage="Programa es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblEmpresa" runat="server" Text="Empresa"></asp:Label>
                                </td>
                                <td>
                                    <input type="text" value="<%=Session["nomEmpresa"]%>" name="txtNewEmpresa" readonly="readonly">
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblNombreRef1" runat="server" Text="Nombre Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewNombreRef1" runat="server" Text='<%# Bind("contr1no") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
                                        ControlToValidate="txtNewNombreRef1"
                                        ErrorMessage="Nombre referencia 1 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblApellidoRef1" runat="server" Text="Apellido Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewApellidoRef1" runat="server" Text='<%# Bind("contr1ap") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server"
                                        ControlToValidate="txtNewApellidoRef1"
                                        ErrorMessage="Apellido referencia1 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblTelefonoRef1" runat="server" Text="Telefono Ref1"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef1" runat="server" Text='<%# Bind("contr1te") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server"
                                        ControlToValidate="txtNewTelefonoRef1"
                                        ErrorMessage="Telefono referencia1 es requerido">*</asp:RequiredFieldValidator>
                                    <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server"
                                        ControlToValidate="txtNewTelefonoRef1"
                                        ErrorMessage="Telefono Referencia1 debe ser un numero"
                                        ValidationExpression="\d+">*</asp:RegularExpressionValidator>
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblNombreRef2" runat="server" Text="Nombre Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewNombreRef2" runat="server" Text='<%# Bind("contr2no") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server"
                                        ControlToValidate="txtNewNombreRef2"
                                        ErrorMessage="Nombre Referencia2 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                                <td>
                                    <asp:Label ID="lblApellidoRef2" runat="server" Text="Apellido Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewApellidoRef2" runat="server" Text='<%# Bind("contr2ap") %>'></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server"
                                        ControlToValidate="txtNewApellidoRef2"
                                        ErrorMessage="Apellido Referencia2 es requerido">*</asp:RequiredFieldValidator>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblTelefonoRef2" runat="server" Text="Telefono Ref2"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef2" runat="server" Text='<%# Bind("contr2te") %>'></asp:TextBox>
                                </td>
                                <td>
                                    <asp:Label ID="lblAnulado" runat="server" Text="Anulado"></asp:Label>
                                </td>
                                <td>
                                    <asp:RadioButtonList ID="RadioButtonList2" runat="server" RepeatDirection="Horizontal"
                                        SelectedValue='<%# Bind("contanul") %>'>
                                        <asp:ListItem Value="S">Si</asp:ListItem>
                                        <asp:ListItem Value="N">No</asp:ListItem>
                                    </asp:RadioButtonList>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <asp:Label ID="lblObservacion" runat="server" Text="Observaciones"></asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtNewTelefonoRef3" runat="server" Rows="5" Text='<%# Bind("contobse") %>'
                                        TextMode="MultiLine"></asp:TextBox>
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                                <td>
                                    &nbsp;
                                </td>
                            </tr>
                        </table>
                        <asp:ValidationSummary ID="ValidationSummary2" runat="server" />
                        <br />
                        <asp:LinkButton ID="btnInsertar" runat="server" CommandName="Insert"
                            TabIndex="13">Insertar</asp:LinkButton>
                        <asp:LinkButton ID="lnkCancelar" runat="server" CommandName="Cancel"
                            TabIndex="14">Cancelar</asp:LinkButton>
                    </InsertItemTemplate>

 

I tried to figure out a solution by assigning ordered tab index, but behaviour keeps the same.  Some controls appear to be validated first with their respective error messages whereas others are validated after the firts ones.

 

thanks in advance.

edotom

Is there any rhyme or reason to which validation messages show?  (ie: do all of the required field validators show first and then the regex validators?)  "If the input control is empty, no validation functions are called and validation succeeds." (from http://msdn.microsoft.com/en-us/library/eahwtc9e.aspx).

Otherwise, take a look to see if some of the validation is occuring on the server instead of the client.  This may also cause the behavior.

The part that is not validated with the other controls is this:

<asp:ObjectDataSource ID="OdsPersona" runat="server" SelectMethod="GetPersonaWithID"
                            TypeName="Facturacion.DAL.PersonaDataLayer" >
                            <SelectParameters>
                            <asp:Parameter DefaultValue="6" Name="tipenume" Type="Int16" />
                             </SelectParameters>
                            </asp:ObjectDataSource>
                            <ajaxToolkit:ComboBox ID="cmbPersona" runat="server"  
                             AutoCompleteMode="Suggest" DataSourceID="OdsPersona"
                             DataTextField="nomCompleto" DataValueField="persnume" Text='<%# Bind("persnume") %>'
                             DropDownStyle="DropDownList" MaxLength="0" style="display: inline;"
                             AppendDataBoundItems="True" TabIndex="1">
                                <asp:ListItem Selected="True" Value="0">Seleccione persona</asp:ListItem>
                         </ajaxToolkit:ComboBox>
                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
                                        ControlToValidate="cmbPersona" ErrorMessage="Persona es requerido"
                                        InitialValue="0">*</asp:RequiredFieldValidator>

All other controls are validated first and when all that is done then this part is validated.  The difference is that its an ajaxtoolkit:combobox.
how can I get that control validated altogether with the others?

I don't think the validator supports the ajaxcontroltoolkit's ComboBox control.  There might be some server-side support (which is probably what you see on the second try), but I wouldn't count on it.  You might have to investigate a making a CustomValidator.

...or try this on for size: http://ajaxcontroltoolkit.codeplex.com/workitem/24417

It is a hack, but it looks like something that might just work.

 

[RESOLVED] Issue in Populating the Error message

Hi,

Can any one let me know about the below issue. I have a page which has three labels, say startdate,enddate and username. My issue is if the user doesnot select any of the above three then a message gets displayed as "Please select one search criteria" or if the user doesnot enter the date in correct format then i  dispaly "Please enter date in mm/dd/yy" format. But what is happening is first time if the user doesnot select any then "Please select one search criteria" is getting displayed and after this message gets displayed if the user enters wrong format of date then both the messages are displayed..how to display only one?

you can use required field validators three of the controls and validation summary.

r24

But what is happening is first time if the user doesnot select any then "Please select one search criteria" is getting displayed and after this message gets displayed if the user enters wrong format of date then both the messages are displayed..how to display only one?

It is a problem with the logic. I might be able to help if you paste your code.

You can get more information about requriredfieldvalidator and validationsummary. you can use requiredexpressionvalidator, to check if the value entered in the date textbox is in date format.

Could you paste your code please, i can reply 5-6 hours later. I think it is an esay task.

Sorry the video tutorial : http://www.totaldotnet.com/Video5.aspx

and there are orhet tutorials about asp.net validation

Hi,

The simple way as it mentioned, is to use validator control to implement your requirement.

<form id="form1" runat="server">
    <div>
              <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="Please select one search criteria"></asp:RequiredFieldValidator>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
            ErrorMessage="Please select one search criteria"></asp:RequiredFieldValidator>

        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3"
            ErrorMessage="Please select one search criteria" Display="Dynamic"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox3"
            ValidationExpression="^((((0[13578])|(1[02]))[\/]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\/]?(([0-2][0-9])|(30)))|(02[\/]?[0-2][0-9]))[\/]?\d{4}$"
            runat="server" ErrorMessage="Please enter date in mm/dd/yy" Display="Dynamic"></asp:RegularExpressionValidator>

  <asp:Button ID="Button1" runat="server" Text="Submit" />

    </div>
    </form>

 

If the problem still exists, please post some code here to let us get more details.

Hope this can help you.