Validate() function doesn't fire - c#

Here is my button.
<asp:Button ID="btnNext" runat="server" Text="Next" Style="display: none" OnClick="btnNext_Click" CausesValidation="true" ValidationGroup="vgLinR"/>
When I write ValidationGroup="vgLinR" in aspx side validation works. But I have 2 different validation group. So I need fire these 2 validation group in one button.
so I write that code at code behind :
protected void btnNext_Click(object sender, EventArgs e)
{
Page.Validate("vgLinR");
Page.Validate("vgLogR");
}
but it doesn't work. Why? How can I do that?

it will work for you ..
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<br />
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="validate all" OnClick="Button1_Click"/> <br />
</div>
</form>
and write code for onclick event
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate();
}

try this
public bool Validate()
{
var isValid = false;
Page.Validate("vgLinR");
isValid = Page.IsValid;
if (isValid)
{
Page.Validate("vgLogR");
isValid = Page.IsValid;
}
return isValid;
}

Saw your answer reply for Amit a bit too late. I have updated my answer accordingly. May be you can use a similar idea if it does not fit your requirement.
In my code I am using a single ValidationSummary control without any validation group specified. Also remove the validation group from your button. Textbox a and b can be in one validation group, vg1 whereas Textbox c and d can be in another, vg2. I am not sure how you have set up your validation groups.
protected void btnNext_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Page.Validate("vg1");
ValidationSummary1.ValidationGroup = "vg1";
}
else if (RadioButton2.Checked)
{
Page.Validate("vg2");
ValidationSummary1.ValidationGroup = "vg2";
}
if (Page.IsValid)
{
//do something in here
}
}
The above code will do a server side validation. To do it on the client side as well, you would need to add a bit of javascript.
Look at another post to enable/disable Validation Group from JQuery or Javascript

Related

Custom Validator won't fire

I'm trying to force the user to choose to fill either the Photo or the Video Textbox using the CustomValidator but it's not working, I've tried searching around and from previous questions a lot of people instructed to add the ValidateEmptyText="true" property, I tried adding it but it still won't fire.
I'm using other RequiredFieldValidators which are operating normally.
This is my aspx code of the two fields:
<asp:Button ID="btn1" runat="server" Text="+"/>
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics" ValidationGroup="txt1"></asp:TextBox>
<br />
<asp:Button ID="btn2" runat="server" Text="+"/>
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos" ValidationGroup="txt1"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidationGroup="txt1" ValidateEmptyText="true"></asp:CustomValidator>
This is my c# Validation method:
public void ValidateBoxes(object sender, ServerValidateEventArgs e)
{
if (string.IsNullOrEmpty(pics.Text) && string.IsNullOrWhiteSpace(vids.Text))
e.IsValid = false;
else
e.IsValid = true;
}
EDIT : This is one of the text boxes and it's validators from the output screen shots.
<asp:TextBox ID ="city_in" PlaceHolder ="Enter city" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="city_in" ErrorMessage="Please enter the city!" ForeColor="Red"></asp:RequiredFieldValidator>
EDIT: This is the whole aspx Code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h1>
Creating An Event
</h1>
<br />
<h3>
Please Provide the information below
</h3>
<asp:TextBox ID ="city_in" PlaceHolder ="Enter city" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="city_in" ErrorMessage="Please enter the city!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID="date" runat="server" PlaceHolder ="Enter date" TextMode="Date" ></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="date" ErrorMessage="Please enter the date!" ForeColor="Red" ></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID="desc" runat="server" PlaceHolder = "Description"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="desc" ErrorMessage="Please enter the description!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID ="entertain" runat="server" PlaceHolder ="Entertainer"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="entertain" ErrorMessage="Please enter the entertainer!" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<asp:TextBox ID ="viewer" runat="server" PlaceHolder ="ID"></asp:TextBox>
<br />
<br />
<asp:TextBox ID ="location" runat="server" PlaceHolder ="Location"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the location!" ControlToValidate="location" ForeColor="Red"></asp:RequiredFieldValidator>
<br />
<br />
<p>
Please choose what type of Multimedia you would like to upload
</p>
<br />
<asp:Button ID="btn1" runat="server" Text="+"/>
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics" ></asp:TextBox>
<br />
<asp:Button ID="btn2" runat="server" Text="+"/>
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<br />
<asp:Button ID ="btn" runat="server" Text="Create Event" OnClick="create_Event" />
<asp:Button runat="server" Text="Cancel" OnClick="go_Profile"/>
Output:
This code was tested and works properly.
<body>
<form id="form1" runat="server">
<p>
Please choose what type of Multimedia you would like to upload
</p>
<br />
<asp:TextBox runat="server" PlaceHolder="Photos" ID="pics"></asp:TextBox>
<br />
<asp:TextBox ID="vids" runat="server" PlaceHolder="Videos"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Please enter either a photo or a picture!" OnServerValidate="ValidateBoxes" ValidateEmptyText="true"></asp:CustomValidator>
<br />
<br />
<asp:Button ID="btn" runat="server" Text="Create Event" />
<asp:Button runat="server" Text="Cancel" />
</form>
</body>
with this code:
public void ValidateBoxes(object sender, ServerValidateEventArgs e)
{
if (string.IsNullOrEmpty(pics.Text) && string.IsNullOrWhiteSpace(vids.Text))
e.IsValid = false;
else
e.IsValid = true;
}
if I enter any value in either of the two textboxes, the Validator is not shown.
I wanted to leave a comment but figured it would be best to display to you exactly what I tested this way you know what is working.
You have to make sure the Page IsValid before creating your event...
protected void btn_Click(object sender, EventArgs e)
{
if (IsValid)
{
Response.Write("Creating an event");
}
}

Why asp.net button is not hiding?

I am facing a weird problem in asp.net forms. I am trying to make button invisible/Inactive but none of my code works in any situation. It remains visible/active.
<asp:Button ID="btnPrintEditedSms" ValidationGroup="Complaints" runat="server" CssClass="btn btn-success"
OnClick="btnPrintEditedSms_Click" Text="Send" />
I am trying to put code here, to make it visible or inactive but not doesn't work although other statements work
protected void GridViewAllSms_SelectedIndexChanged(object sender, EventArgs e)
{
BtnPrintEditedSms.Visible = false; //this doesn't work
BtnPrintEditedSms.Enabled = false; //this also
txtComplainant.Visible = true; //this works
}
It is within Update Panel:
<asp:UpdatePanel ID="updGridViewSMS" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<label><b>Search By Date Range</b></label>
<asp:Label ID="lblDateFrom" runat="server" Text="From"></asp:Label>
<asp:TextBox ID="txtFromDate" runat="server" ></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderFromDate" Format="dd/MMM/yyyy" TargetControlID="txtFromDate" runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server"
ControlToValidate="txtFromDate" Display="None" ErrorMessage=""
ForeColor="Red" >
</asp:RequiredFieldValidator>
<asp:Label ID="lblDateTo" runat="server" Text="To"></asp:Label>
<asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderToDate" Format="dd/MMM/yyyy" TargetControlID="txtToDate" runat="server">
</asp:CalendarExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server"
ControlToValidate="txtToDate" Display="None" ErrorMessage=""
ForeColor="Red" >
</asp:RequiredFieldValidator>
<asp:Button ID="btnSearchByDate" CssClass="btn btn-success" runat="server" Text="Search"
ClientIDMode="Static" OnClick="btnSearchByDate_Click" />
<asp:Button ID="btnEdit" CssClass="btn btn-success" runat="server" Text="Edit"
ClientIDMode="Static" OnClick="btnEdit_Click" />
</asp:UpdatePanel>
try this
protected void GridViewAllSms_SelectedIndexChanged(object sender, EventArgs e)
{
BtnPrintEditedSms.Visible = false; //this doesn't work
BtnPrintEditedSms.Enabled = false; //this also
txtComplainant.Visible = true; //this works
Updatepanel1.Update();
}
or if you dont want to set your update mode set to conditional then set it to always like
<asp:UpdatePanel ID="Updatepanel1" runat="server" UpdateMode="Always">

Validation on a button click using RequiredFieldValidator

In the past, on button click events, I've validated without using RequiredFieldValidators. However, I thought I'd learn about them and implement them.
My old approach:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals(""))
{
lblMessage.Text = "Please check all fields have been entered.";
}
//else if ...further validation statements e.g. check lengths
}
However, using RequiredFieldValidators with the same example, am I correct in saying that I don't have to check again if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals("")) like below or is it good practice to do so?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//...further validation statements e.g. check lengths
try
{
SendMail();
}
catch (Exception)
{
}
}
}
If I should still include the line, it should go at the beginning of the if (Page.IsValid), right?
HTML code:
<p>Contact Form</p>
<p>
Your name:
<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="*"
ControlToValidate="txtName" ValidationGroup="save" /><br />
<asp:TextBox ID="txtName" runat="server" Width="250px" /><br />
Your email address:
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="*"
ControlToValidate="txtEmail" ValidationGroup="save" /><br />
<asp:TextBox ID="txtEmail" runat="server" Width="250px" />
<asp:RegularExpressionValidator runat="server" ID="rfvEmail2"
SetFocusOnError="true" Text="Example: email#gmail.com" ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
ValidationGroup="save" /><br />
Subject:
<asp:RequiredFieldValidator ID="rfvSubject" runat="server" ErrorMessage="*"
ControlToValidate="txtSubject" ValidationGroup="save" /><br />
<asp:TextBox ID="txtSubject" runat="server" Width="400px" /><br />
Comments:
<asp:RequiredFieldValidator ID="rfvComments" runat="server" ErrorMessage="*"
ControlToValidate="txtComments" ValidationGroup="save" /><br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="10" Width="400px" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick="btnSubmit_Click" ValidationGroup="save" />
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Visible="true" />
</p>
why dont you do the following?
Page.Validate("save");
if (Page.IsValid)
{
//Continue with your logic
}
else
{
//Display errors, hide controls, etc.
}
This only fires your validation group and furthermore , you can use a validation summary to display your message about the correct formats of the text boxes.
And you can display an error message then and there to display the correct format.

Form submits on browser refresh

I am having trouble to find a solution to stop form submission on click of the browser's refresh button.
This is the Login form I have:
<asp:Login ID="EMSLogin" runat="server" OnAuthenticate="EMSLogin_Authenticate">
<LayoutTemplate>
<asp:Panel ID="Panel1" runat="server" CssClass="wrapper">
<asp:Panel ID="Panel2" runat="server" CssClass="holder">
<asp:Panel ID="Panel3" runat="server" CssClass="loginBox one_edge_shadow">
<h1>
Login Credentials</h1>
<asp:Panel ID="Panel4" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel5" runat="server" CssClass="label">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel6" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="UserName" runat="server" Height="16px" Width="165px" Font-Size="14px"
Font-Names="Arial Sans-Serif" ToolTip="Enter your valid login name" />
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
</asp:Panel>
<asp:Panel ID="Panel7" runat="server" CssClass="name topmargin">
<asp:Panel ID="Panel8" runat="server" CssClass="label">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
</asp:Panel>
<asp:Panel ID="Panel9" runat="server" CssClass="textBox">
<telerik:RadTextBox ID="Password" runat="server" TextMode="Password" Height="16px"
Width="165px" Font-Size="14px" Font-Names="Arial Sans-Serif" ToolTip="Enter your valid password" />
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
ValidationGroup="EMSLogin">*</asp:RequiredFieldValidator>
</asp:Panel>
<br class="clearfix" />
<telerik:RadButton ID="LoginButton" runat="server" CommandName="Login" Text="Log In"
CssClass="loginButton" Font-Size="14px" Width="100px" ValidationGroup="EMSLogin"
ToolTip="Click to log in" />
</asp:Panel>
</asp:Panel>
</asp:Panel>
</asp:Panel>
</LayoutTemplate>
</asp:Login>
And in the backend:
protected void Page_Load(object sender, EventArgs eventArgs) {
log.Info("=============INSIDE Page_Load======");
DataBind();
LoginErrorWindow.VisibleOnPageLoad = false;
}
protected void EMSLogin_Authenticate(object sender, AuthenticateEventArgs e) {
log.Info("=============INSIDE EMSLogin_Authenticate======");
RadTextBox UserName = EMSLogin.FindControl("UserName") as RadTextBox;
RadTextBox Password = EMSLogin.FindControl("Password") as RadTextBox;
if (Membership.ValidateUser(UserName.Text, Password.Text)) {
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
} else {
LoginErrorWindow.NavigateUrl = EMSApplication.Web.Utils.NavigationUtils.GetLoginErrorDialogURL();
LoginErrorWindow.VisibleOnPageLoad = true;
}
}
Now after one login failed if I press the refresh button the method EMSLogin_Authenticate is executing again. And before reload it is showing:
How can I solve this?
Do a Response.Redirect to an error page after the login has failed.
See the PRG pattern on Wikipedia.
Post/Redirect/Get (PRG) is a web development design pattern that prevents some duplicate form submissions, creating a more intuitive interface for user agents (users). PRG implements bookmarks and the refresh button in a predictable way that does not create duplicate form submissions.

HOw to call custom validtor on page load?

On the page load i wanna call a custom validator which validates my page and display corresponding error messages.
How can i do this?
I am using javascript in the custom validator.
You can use Page.IsValid and Page.Validate()
http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx
After Edit: // Here is a working sample:
JS:
<script type="text/javascript">
function EmpIDClientValidate(ctl, args) {
// the value is a multiple of 5 if the module by 5 is 0
args.IsValid = (args.Value % 5 == 0);
}
</script>
Aspx:
<table>
<tr>
<td>
ID (multiple of 5):
</td>
<td>
<asp:TextBox runat="server" Width="200px" ID="EmpID" Text="12"/>
<asp:RequiredFieldValidator runat="server" ID="ValidateEmpID" ControlToValidate="EmpID"
ErrorMessage="ID is required" Display="dynamic">*
</asp:RequiredFieldValidator>
<asp:CustomValidator runat="server" ID="ValidateEmpID2" ControlToValidate="EmpID"
ClientValidationFunction="EmpIDClientValidate" ErrorMessage="ID must be a multiple of 5"
Display="dynamic" OnServerValidate="ValidateEmpID2_ServerValidate">*
</asp:CustomValidator>
</td>
</tr>
</table>
<br />
<asp:Button runat="server" Text="Submit" ID="Submit" OnClick="Submit_Click" /><br />
<br />
<asp:CheckBox runat="server" ID="chkEnableValidators" Checked="True" AutoPostBack="True"
Text="Validators enabled" OnCheckedChanged="OptionsChanged" />
<br />
<asp:CheckBox runat="server" ID="chkEnableClientSide" Checked="True" AutoPostBack="True"
Text="Client-side validation enabled" OnCheckedChanged="OptionsChanged" />
<br />
<asp:CheckBox runat="server" ID="chkShowSummary" Checked="True" AutoPostBack="True"
Text="Show summary" OnCheckedChanged="OptionsChanged" />
<br />
<asp:CheckBox runat="server" ID="chkShowMsgBox" Checked="False" AutoPostBack="True"
Text="Show message box" OnCheckedChanged="OptionsChanged" />
<br />
<br />
<asp:ValidationSummary runat="server" ID="Summary" DisplayMode="BulletList" HeaderText="<b>Please review the following errors:</b>"
ShowSummary="true" />
<asp:Label runat="server" ID="Result" ForeColor="magenta" Font-Bold="true" EnableViewState="False" />
And codebehind:
protected void Page_Load(object sender, EventArgs e)
{
// To run all validators
Page.Validate();
// To run just one validator:
ValidateEmpID2.Validate();
}
protected void Submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
Result.Text = "Thanks for sending your data";
else
Result.Text = "There are some errors, please correct them and re-send the form.";
}
protected void ValidateEmpID2_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
args.IsValid = (int.Parse(args.Value) % 5 == 0);
}
catch
{
args.IsValid = false;
}
}
protected void OptionsChanged(object sender, EventArgs e)
{
// Examine all the validators on the back.
foreach (BaseValidator validator in Page.Validators)
{
// Turn the validators on or off, depending on the value
// of the "Validators enabled" check box (chkEnableValidators).
validator.Enabled = chkEnableValidators.Checked;
// Turn client-side validation on or off, depending on the value
// of the "Client-side validation enabled" check box
// (chkEnableClientSide).
validator.EnableClientScript = chkEnableClientSide.Checked;
}
// Configure the validation summary based on the final two check boxes.
Summary.ShowMessageBox = chkShowMsgBox.Checked;
Summary.ShowSummary = chkShowSummary.Checked;
}
Page.Validate(), assuming you are using the CustomValidator server control
You can call the function as
<body onload ="Functionname()">
In case of javascript can use as onload="javascript:functionname();"

Categories