ASPX validation controllers not displaying messages - c#

So this is what i have
protected void submitEmail_Click(object sender, EventArgs e)
{
try
{
if (!Page.IsValid)
{
validationMsg.Visible = true;
validationMsg.Text = "Please insert a valid email address.";
return;
}
if (!IsValidEmail())
{
validationMsg.Visible = true;
validationMsg.Text = "Please insert a valid email address.";
return;
}
SaveData();
validationMsg.Visible = true;
validationMsg.Text = "Thank you for joining our beta community! We’ll send word as soon as our beta is out.";
}
catch (Exception ex)
{
}
}
And a .aspx :
<%# Control Language="C#"
AutoEventWireup="true"
CodeFile="BetaEmailUserForm.ascx.cs"
Inherits="CMSWebParts_BullGuard_User_Forms_BetaEmailUserForm" %>
<div class="subscribe">
<asp:TextBox ID="userEmail" runat="server"
CssClass="subscribe-input"></asp:TextBox>
<asp:LinkButton ID="submitEmail" runat="server"
OnClick="submitEmail_Click"
CssClass="subscribe-submit button"
CausesValidation="true"
ValidationGroup="betaEmailGroup">
<span style="font-size: 20px; color: #ffffff;padding: 26px;display:block;">✓</span>
</asp:LinkButton>
</div>
<p class="thank">
<asp:Literal ID="validationMsg"
runat="server"
Visible="false"></asp:Literal>
<asp:RequiredFieldValidator ID="rfvEmail1new"
ControlToValidate="userEmail"
SetFocusOnError="true"
EnableClientScript="true"
ValidationGroup="betaEmailGroup"
runat="server"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail1new"
ControlToValidate="userEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
SetFocusOnError="true"
EnableClientScript="true"
ValidationGroup="betaEmailGroup"
runat="server"></asp:RegularExpressionValidator>
</p>
What i want is this.
case 1 : i enter nothing in the input filed the 1st validator takes action and in the .cs file i assume that the 1st condition should fail, resulting in adding the message
case 2 : i enter an invalid email address => same logic as for case 1
case 3 : enter a good email address skip the 2 checks
case 4 : enter an already registered email address ==> go to 2nd check condition.
The issue is that i don't get the messages displayed for the 2 Validators.
1st case I don't enter any data i want to go with the following case
if (!Page.IsValid)
It does not happen.
2nd case that fails is if the email address is not correct (eg. asdasd#dadad)
should also go with the case where page is not valid
if (!Page.IsValid)
I've tried to debug butcouldn't debug for the 1st and 2nd test cases.
I can debug only if i enter a valid email address.
Any help? thank you.
I'm thinking that there are some client side validation that the aspx controllers will do for me in the back without my knowledge, some js generated files? don't know

I wish the problem is for "!Page.IsValid".
Look at the following links
https://msdn.microsoft.com/en-us/library/system.web.ui.page.isvalid(v=vs.110).aspx
How does Page.IsValid work?
Sometimes need to add " ErrorMessage="" " to the validations tag. Please also check it.
I wish this will help you.
There is also others easy way to do this job which is build in, you can follow them.

Related

Can not validate empty input field using c# asp.net

I can not validate for empty input field using c# asp.net. Actually I have two input field. I need to display validation message for blank input field. I have done some coding. When I am clicking on submit button without giving any input, I am getting the error message for first input filed i.e., Name field can not be blank and one red color border on that input field. When I am giving any input to first input field and again clicking on submit button the error message for second input field is coming but problem is border color is showing red in first input field which should not come. I am explaining my code below.
index.aspx:
<div class="widget-title">Doctor Registration <span id="validationMessage" runat="server" ></span></div>
<div class="row doctorlist-form">
<div class="col-md-6 bmargindiv1">
<label for="doctorname" accesskey="N"><span class="required">*</span> Name</label>
<div class="col-md-2 padding-zero">
<asp:DropDownList ID="txtdoctorprefix" name="doctorname" runat="server">
<asp:ListItem Value="Dr." Selected="True" Text="Dr."></asp:ListItem>
<asp:ListItem Value="Mr." Text="Mr."></asp:ListItem>
<asp:ListItem Value="Mrs." Text="Mrs."></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-10 padding-zero"><asp:TextBox ID="txtDoctorName" runat="server" oninput="detectName('dName');" ></asp:TextBox></div>
<div class="clearfix"></div>
</div>
<div class="col-md-6 bmargindiv1">
<label for="gender" accesskey="G"><span class="required">*</span> Gender</label>
<asp:DropDownList ID="txtGender" name="grnder" runat="server" onchange="selectGender('gender');">
<asp:ListItem Text="Select your Gender" Selected="True"></asp:ListItem>
<asp:ListItem Text="Male" Value="male" ></asp:ListItem>
<asp:ListItem Text="Female" Value="female"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-12 bmargindiv1">
<asp:Button runat="server" Text="Submit" class="button" ID="doctorDetails" OnClick="doctorDetails_Click" />
</div>
</div>
<script type="text/javascript">
function detectName(nameid) {
var type = nameid;
console.log(type);
switch (type) {
case 'dName':
$('#<%=txtDoctorName.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
function selectGender(type) {
var type = type;
switch (type) {
case 'gender':
$('#<%=txtGender.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
</script>
index.aspx.cs:
protected void doctorDetails_Click(object sender, EventArgs e)
{
// Response.Write(txtDoctorName.Text.Trim().Length);
if (txtDoctorName.Text.Trim().Length == 0 )
{
validationMessage.InnerText = "Name field can not be blank.";
validationMessage.Style.Add("color", "red");
txtDoctorName.Focus();
txtDoctorName.BorderColor = System.Drawing.Color.Red;
return;
}
if (txtGender.SelectedIndex==0)
{
validationMessage.InnerText = "Gender field can not be blank.";
validationMessage.Style.Add("color", "red");
txtGender.Focus();
txtGender.BorderColor = System.Drawing.Color.Red;
return;
}
}
My problem is when total field is blank and I am clicking on submit button the error message is coming properly but at the same time when I am giving some input to 1st text field and again clicking on submit button the 1st if statement is also executing along with the second if statement which should not happen. In this case only second if statement should execute. Please help me to resolve this issue.
I strongly recommend using the ASP.NET validation controls. For example:
ASPX Page
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="Default" />
<asp:TextBox ID="txtDoctorName" runat="server" />
<asp:CustomValidator
ID="cv"
runat="server"
ControlToValidate="txtDoctorName"
ValidateEmptyText="true"
Text="*"
OnServerValidate="ValidateRequired"
ErrorMessage="Please enter a valid Doctor Name."
ValidationGroup="Default" />
Code Behind
protected void SubmitOnClick(object sender, EventArgs e)
{
if (!Page.IsValid) return;
...
}
protected void ValidateRequired(object source, ServerValidateEventArgs args)
{
args.IsValid = !string.IsNullOrEmpty(args.Value.Trim());
}
The ValidationSummary will give you a nice listing of all validation errors, rather than just one at a time.
If you're going to continue with this method, to fix the red border on the first text box not going away, you will need to reset the border color each time the button is clicked:
protected void doctorDetails_Click(object sender, EventArgs e)
{
// Clear all properties each time the button is clicked
validationMessage.InnerText = string.Empty;
txtDoctorName.BorderColor = System.Drawing.Color.Black;
txtGender.BorderColor = System.Drawing.Color.Black;
if (txtDoctorName.Text.Trim().Length == 0 )
{
...
}
You can start your project in Debug mode (F5), place a break point on the doctorDetails_Click method, and step through using F10 to see more details about what's going on.
Since you set the color of the border explicitly on a control that is running at server (runat) - my strong hunch is that the ViewState is preserving these properities.
You can test that behaviour by reversing your code to check on the second input before the first, you may see that red border remains on the second now while (only) the first has failed validation
I agree with #GoatBreeder that you use buitin validation controls,

Obtaining control Id through javascript in asp.net

I have a scenario in my asp.net application where when enter button is keyed in any of the multiline textboxs, I need to add a particular length to the existing length and show it in another control. I have written a generic javascript function to handle key-in in "pnlEnglish" panel. I can find out "Enter key" key up by checking "e.keycode ==13" , However would it be possible to know from which control I am firing the event??. I am trying to avoid adding events to text box since, I have to handle it for too many. Is there any better solution to achieve this??
<asp:Panel ID="pnlEnglish" runat="server">
<asp:TextBox ID="txtPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px" TabIndex="12"></asp:TextBox>
<asp:TextBox ID="txtLegacyPlot" runat="server" Rows="5" TextMode="MultiLine" Width="350px"TabIndex="12"></asp:TextBox>
</asp:Panel>
Javascript is as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
//Need to identify the control for which I shall add the length
}
var txtLenPlot = $('#<%=txtPlot.ClientID%>').val().length;
var txtLenLegacyPlot = $('#<%=txtLegacyPlot.ClientID%>').val().length;
//The below function shows the length in length displaying control
update_chars_left(500, $('#<%=txtLengthPlot.ClientID %>'), txtLenPlot);
update_chars_left(205, $('#<%=txtLengthLegacyPlot.ClientID %>'), txtLenLegacyPlot);
});
In side key up function you can get id of textbox in which enter key is pressed as below
$('#<%=pnlEnglish.ClientID%> input:text,#<%=pnlEnglish.ClientID%> textarea').keyup(function (e) {
if (e.keyCode == 13) {
var currTextboxId = $(this).attr('id');
//Your Code
});

Responding to an "enter" keypress within an <input> field

My question is about handling Enter key press.I have one page called "order.aspx" which is residing inside master page.Here i am explaining the control structure
1. <asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
2. <asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
3. one asp grid control with one column containing textbox for entering order quantity
4. <asp:Button ID="btnOrder" runat="server" OnClick="btnOrder_Click" />.
My requirement is,
while user enter text in the search textbox and press enter key then btnSearch_Click should fire
while user enter quantity in the grid textbox and press enter key then btnOrder_Click should fire.
I tried with different code finally got answers but it is not fully functional.Follwing is the javascript code i have used.
function DoEnterKeyButtonClick(buttonId) {
e = event;
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
document.getElementById('ctl00_CphMaster_' + buttonId).click();
return false;
}
}
I am calling this method on key press of txtSearch and grid textbox and passing the Button id to fire event btnSearch and btnOrder respectively.When i am entering the text in the search textbox and hitting the enter key then btnSearch_Click is firing and when i am entering the order quantity and hitting the enter key the btnOrder_Click is firing.But the issue is,after changing the page index say second page the required functionality not working.That is when i am entering order quantity and hitting the enter key then btnSearch_Click will fire first , then btnOrder_Click firing.This will clear the quantity entered and results in error.Please help me...
Thanks,
Joby
Instead of giving this document.getElementById('ctl00_CphMaster_' + btnSearch).click();
Try this document.getElementById('<%= btnSearch.ClientID %>').click();
or try using jquery
$("#txtSearch").keyup(function(event){
if(event.keyCode == 13){
$("#btnSearch").click();
}
});
Else place your controls inside the asp:panel and set the DefaultButton property as btnSearch as like below
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<asp:TextBox ID="txtSearch" MaxLength="50" runat="server" Width="420px" CssClass="txtbox"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" />
</asp:Panel>
Hope this will help.
Many Thanks
Anna
Your function doesn't know what exactly this even is.
Try it like this
function DoEnterKeyButtonClick(event,buttonId){}
I keep the following handy snippet around..
function getIntKey(key) {
var keycode;
if (key == null) { keycode = event.keyCode; } else { keycode = key.keyCode; }
return keycode;
}
And use it, like this..
$("#txtSearch").keyup(function(e){
if(getIntKey(e) == 13){
//Enter was pressed, do somthing
}
});

Password custom validation ain't working

I have a form for registration.
I'm checking if the password has 6 characters like this :
<input type="password" runat="server" name="password" size="41" maxlength="64" id="txtpassword" /><span>*</span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server" ErrorMessage="Fill in a password." ControlToValidate="txtpassword"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="valPassword" ErrorMessage="Password must be 6 characters long." ControlToValidate="txtpassword"></asp:CustomValidator> (at least 6 characters)
codebehind
protected void valPassword(object source, ServerValidateEventArgs args)
{
args.IsValid = ValidatePassword(args.Value);
}
private bool ValidatePassword(string pw)
{
if (pw.Length >= 6)
{
return true;
}
else
{
return false;
}
}
If I leave the RequiredFieldValidator and the CustomValidator work together and I fill in 1 character , the form is accepted.
If I delete the RequiredFiekdValidator and fill in the form, the form is accepted with no character at all in the passwordfield
If I leave the CustomValidator and I fill in 1 character , the form is accepted
My CustomValidator isn't working properly, what am I missing ?
try changing txtpassword to an <asp:Textbox> instead of an input.
maybe a problem with name vs id? I usually try to have the name and the id of an element match to avoid confusion.

DotNetOpenAuth - OnLoggedIn not firing on OpenIdButton

I am trying to implement OpenID for a website using only Google as the authentication provider. I am using the OpenIdButton control to send users to their Google Apps login since I always want them to go to the same place.
The button sends them to the right place and returns them to the ReturnToUrl correctly but it doesn't seem that the OnLoggedIn event ever fires. I am checking the event by setting a TextBox value in the method and I am seeing no change in the TextBox value. Here is my code...
<tr>
<td>
<asp:TextBox ID="devMsg" runat="server"/>
</td>
</tr>
<tr>
<td valign="top" align="center">
<font size="-1"><b>Sign in with your</b></font>
<br />
<br />
<rp:OpenIdButton ID="OpenIdButton1" runat="server" Text="Login with your Google account!"
ImageUrl="http://www.google.com/accounts/google_transparent.gif"
Identifier="https://www.google.com/accounts/o8/site-xrds?hd=dev.connexcloud.com"
ReturnToUrl="http://localhost:1587/OpenIdRelyingPartyWebForms/loginGoogleApps.aspx"
OnLoggedIn="OpenIdLogin_LoggedIn" />
<br />
<br />
<font size="-1"><b>Account</b></font>
</td>
</tr>
protected void OpenIdLogin_LoggedIn(object sender, OpenIdEventArgs e)
{
this.devMsg.Text = "no response";
if (e.Response != null)
{
devMsg.Text = "response";
switch (e.Response.Status)
{
case AuthenticationStatus.Authenticated:
this.devMsg.Text = "authenicated";
break;
case AuthenticationStatus.Canceled:
this.devMsg.Text = "canceled";
break;
case AuthenticationStatus.Failed:
this.devMsg.Text = "failed";
break;
}
}
}
The TextBox is never being set to anything so it looks to me like the OpenIdLogin_LoggedIn call is never being made when the response is coming back from Google.
Have you tried setting a breakpoint in your LoggedIn handler? I suspect it's working. After the LoggedIn handler is invoked, the control calls FormsAuthentication.RedirectFromLoginPage with the OpenID claimed identifier, which would scrub the TextBox that you're setting in it before you noticed it.
Another way besides a breakpoint you can test it is by setting e.Cancel = true in your handler, which suppresses the subsequent call to FormsAuthentication.RedirectFromLoginPage.

Categories