HOw to call custom validtor on page load? - c#

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();"

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");
}
}

Logout linkbutton is not firing click event

I am trying to implement my login and logout through my webpage. There are two panels which toggle. On my page load, the logout panel is made invisible so that the user may only see the login link. After logging in the login panel is made invisible and the logout panel is made visible where the logout link is there for logging out. but the logout linkbutton is not even firing the click event. This is what i see in the browser window at the bottom when i try to click the logout link button
This is my aspx page-
<div>
<asp:Panel ID="LoginPanel" runat="server">
<ul class="style1">
<li>Username</li>
<li><asp:TextBox ID="LoginEmail" runat="server" Width="90%" placeholder="Email" class="form-control"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Email Required" ControlToValidate="LoginEmail" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li>Password</li>
<li><asp:TextBox ID="LoginPassword" runat="server" Width="90%" placeholder="Password" class="form-control" TextMode="Password"></asp:TextBox></li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Password Required" ControlToValidate="LoginPassword" ForeColor="#CC0000" Font-Italic="True"></asp:RequiredFieldValidator>
<li><asp:Button ID="LoginButton" runat="server" Text="Login" class="btn btn-default" onclick="LoginButton_Click"/>
New User?<asp:HyperLink ID="new_user" runat="server" NavigateUrl="Registration.aspx">Register Here</asp:HyperLink></li>
</ul>
</asp:Panel>
<asp:Panel ID="LogoutPanel" runat="server">
<asp:LinkButton ID="LogoutLink" runat="server" Text="Logout"
onclick="LogoutLink_Click" />
</asp:Panel>
</div>
This is my cs code-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class UserMasterPage : System.Web.UI.MasterPage
{
ConnectionClass cl;
SqlDataReader dr;
string sql;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LogoutPanel.Visible = false;
cl = new ConnectionClass();
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
sql = "select Id, Email_, Password_, Block from MemberLogin where Email_='" + LoginEmail.Text + "'";
cl = new ConnectionClass();
cl.establishConnection();
cl.createReaderCommand(sql);
dr = cl.executeReaderCommand();
if (dr.HasRows)
{
if (LoginPassword.Text == dr["Password_"].ToString())
{
if (dr["Block"].ToString() == "False")
{
Session["user"] = dr[0].ToString();
LoginPanel.Visible = false;
LogoutPanel.Visible = true;
//Response.Write("login successful");
}
}
}
cl.closeConnection();
}
protected void LogoutLink_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("AdminLogin.aspx");
}
}
This is on my master page. I need to solve this problem very soon. Please help me with this.Thanks in advance.
The __DoPostBackWithOptions call associated with the LinkButton is related to the presence of the validators in your page. Setting CausesValidation to false would replace it by the "regular" __doPostBack:
<asp:LinkButton ID="LogoutLink" runat="server" CausesValidation="false" ... />
The validators shown in your markup being in a Panel with Visible = false, they should not be active. But since I don't see anything else that could prevent the postback, turning off the validation for the LinkButton would at least eliminate that possible cause.
By the way, if you have many controls and validators in your form, you may consider grouping them with validation groups. That would allow each button (or other controls causing a postback) to trigger only the relevant validators:
<asp:TextBox ID="txt1a" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1a" runat="server" ControlToValidate="txt1a" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt1b" runat="server" ValidationGroup="Group1" />
<asp:RequiredFieldValidator ID="rfv1b" runat="server" ControlToValidate="txt1b" ValidationGroup="Group1" Text="*" ForeColor="Red" />
<asp:Button ID="btn1" runat="server" Text="Button1" ValidationGroup="Group1" />
<br />
<asp:TextBox ID="txt2a" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2a" runat="server" ControlToValidate="txt2a" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:TextBox ID="txt2b" runat="server" ValidationGroup="Group2" />
<asp:RequiredFieldValidator ID="rfv2b" runat="server" ControlToValidate="txt2b" ValidationGroup="Group2" Text="*" ForeColor="Red" />
<asp:Button ID="btn2" runat="server" Text="Button2" ValidationGroup="Group2" />
In the example above, a click on btn1 would cause a postback even if txt2a is empty, because they don't belong to the Group1 validation group.

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.

Validate() function doesn't fire

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

Categories