简体   繁体   中英

How to display Validation Message from code behind

I have one textbox.. i want to validate it's value based on dropdownlist value.. So i am displaying message from code behind using RegularExpressionValidator .. But it is not working plz,give me suggestion..

<asp:TextBox ID="tbnooflecture" runat="server"  Width="119px" Height="33px"></asp:TextBox>

              <asp:RegularExpressionValidator ID="RegularExpressionValidator1"  ForeColor="#6600FF" 
                runat="server"  ValidationGroup="upper" 
                     ControlToValidate="tbnooflecture"></asp:RegularExpressionValidator>
 <asp:Button ID="bfillattendence" runat="server" Text="To Fill Attendence Click Here"
                            onclick="FillAttendence_Click" Width="218px"  Height="33px" CausesValidation="true" ValidationGroup="upper"/>

i am writing below code in Button click event

string  batchname = dpbatchname.SelectedItem.Text.ToString();
        int lengthofbatch=batchname.Length;
        if(lengthofbatch==2)
        {
            RegularExpressionValidator1.ValidationExpression = "[1-9][02468]|[02468]";

        RegularExpressionValidator1.ErrorMessage = "Only Even No. of Attendence is Valid for Lab.";
        }
        else if (lengthofbatch == 1)
        {
            RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
            RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
        }
        else
        {
            RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
            RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
        }

Are you validating Textbox value? If you use regular expression on server side, then you need to validate input (your textbox) like below, and display message.

if (Regex.IsMatch(text, reg))
{

}

Add this line RequiredFieldValidator1.IsValid = false;

after

RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]"; RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM