Conditional Custom Validation on 2 TextBoxes - c#

My goal here is to build a field that will basically make one or the other textbox required. I.E. If one textbox has some value that is not null, whitespace. or empty, I want the submit button to proceed. Else I want the standard red error to stop the submit from postingback and launching the insert function. I have tried writing this, but so far no good. What can I do to make this work?
<script type="text/javascript">
function validateText(sender, args) {
if (args.value !== "") {
var textBoxB = document.getElementById('TextBox12');
args.IsValid = (TextBox12.value !== "");
}
return;
/*
if (!string.IsNullOrEmpty(TextBox12.Text + TextBox13.Text)) {
args.IsValid = true;
}
else {
if (string.IsNullOrEmpty(TextBox12.Text) && !string.IsNullOrEmpty(TextBox13.Text)) {
args.IsValid = true;
}
else if (string.IsNullOrEmpty(TextBox13.Text) && !string.IsNullOrEmpty(TextBox12.Text)) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
*/
}
</script>
<div>
<div class="left">
<asp:Label ID="Label13" runat="server" Text="Advanced Cancellation:"></asp:Label>
</div>
<div class="right">
<asp:TextBox ID="TextBox12" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Required"
ValidationGroup='valGroup1'
ClientValidationFunction="validateText"
OnServerValidate="ServerValidation"
ForeColor="Red"
ValidateEmptyText="true">
</asp:CustomValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="Advanced Cancellation must be an integer."
ControlToValidate="TextBox12"
ValidationExpression="^\+?(0|[1-9]\d*)$"
ForeColor="Red">
</asp:RegularExpressionValidator>
</div>
</div>
<div>
<div class="left">
<asp:Label ID="Label14" runat="server" Text="Action Required (yyyy-MM-dd):"></asp:Label>
</div>
<div class="right">
<asp:TextBox ID="TextBox13" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server"
ValidationGroup='valGroup1'
ValidateEmptyText="true"
ErrorMessage="Required"
ClientValidationFunction="validateText"
OnServerValidate="ServerValidation"
ForeColor="Red">
</asp:CustomValidator>
<asp:CompareValidator
ID="CompareValidator1" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="TextBox13"
ErrorMessage="Please enter a valid date."
ForeColor="Red">
</asp:CompareValidator>
</div>
</div>
protected void ServerValidation(object source, ServerValidateEventArgs args)
{
if (!string.IsNullOrEmpty(TextBox12.Text))
args.IsValid = !string.IsNullOrEmpty(TextBox13.Text);
}
That's what I have so far.

I have remove javascript code.Now your design part is
<div>
<div class="left">
<asp:Label ID="Label13" runat="server" Text="Advanced Cancellation:"></asp:Label>
</div>
<div class="right">
<asp:TextBox ID="TextBox12" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Required"
ValidationGroup="valGroup1"
OnServerValidate="ServerValidation"
ForeColor="Red"
ValidateEmptyText="true">
</asp:CustomValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ErrorMessage="Advanced Cancellation must be an integer."
ControlToValidate="TextBox12"
ValidationExpression="^\+?(0|[1-9]\d*)$"
ForeColor="Red">
</asp:RegularExpressionValidator>
</div>
</div>
<div>
<div class="left">
<asp:Label ID="Label14" runat="server" Text="Action Required (yyyy-MM-dd):"></asp:Label>
</div>
<div class="right">
<asp:TextBox ID="TextBox13" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server"
ValidationGroup="valGroup1"
ValidateEmptyText="true"
ErrorMessage="Required"
OnServerValidate="ServerValidation"
ForeColor="Red">
</asp:CustomValidator>
<asp:CompareValidator
ID="CompareValidator1" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="TextBox13"
ErrorMessage="Please enter a valid date."
ForeColor="Red">
</asp:CompareValidator>
</div>
</div>
<div>
<asp:Button ID="btnok" runat="server" ValidationGroup="valGroup1" />
</div>
and code behind is
protected void ServerValidation(object source, ServerValidateEventArgs args)
{
if (!string.IsNullOrEmpty(TextBox12.Text) || !string.IsNullOrEmpty(TextBox13.Text))
args.IsValid = true;
else
{
args.IsValid = false;
}
}
I have tested its work for me

Related

AsyncFileUpload in Repeater in UpdatePanel

The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.
<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
<ContentTemplate>
<div class="field-group list-of-resource">
<asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
<ItemTemplate>
<div class="resource">
<div class="remove-input">
<asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
<span>Remove</span>
</div>
<h2>Details of Resources
<span class="counter">
<asp:Literal ID="LitCount" runat="server"></asp:Literal>
</span>
</h2>
<ul>
<li>
<fieldset class="form-group">
<legend>Accession No.</legend>
<asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Details</legend>
<asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Image</legend>
<ajaxToolkit:AsyncFileUpload runat="server"
ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="add-input">
<asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
<span>Add another request</span>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
</Triggers>
</asp:UpdatePanel>
First add command name to linkbutton and remove click event:
<asp:LinkButton ID="LbAddRequest" runat="server"
CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
And try this ItemCommand event in code-behind to get in work:
protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRequest")
{
FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
if (myFileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(myFileUpload.FileName);
myFileUpload.SaveAs(Server.MapPath("~/") + filename);
myStatusLabel.Text = "Upload Success";
}
catch (Exception ex)
{
myStatusLabel.Text = "Upload Fail" + ex.Message;
}
}
else
{
myStatusLabel.Text = "myFileUpload Has No File";
}
}
}
Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File

null reference exception on page redirect

I'm getting a null reference exception on singleKingButton.Checked = true; in the page load event. If I comment it out then I still get one on the next line setting the date. The odd thing is the page loads fine it's when I hit the submit button that I get the error. Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace garrettPenfieldUnit4
{
public partial class Default : System.Web.UI.Page
{
Reservation newReservation = new Reservation();
//Load events, automatically inserts todays date and selects the single king radio button
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
singleKingButton.Checked = true;
arrivalDateBox.Text = DateTime.Today.ToShortDateString();
}
//When submit button is clicked show the two confirmation labels.
protected void submitButton_Click(object sender, EventArgs e)
{
newReservation.ArrivalDate = Convert.ToDateTime(arrivalDateBox.Text);
newReservation.DepartureDate = Convert.ToDateTime(departureDateBox.Text);
newReservation.NoOfPeople = peopleDropDown.SelectedIndex;
newReservation.SpecialRequests = specialRequestsBox.Text;
newReservation.FirstName = firstNameBox.Text;
newReservation.LastName = lastNameBox.Text;
newReservation.Email = addressBox.Text;
newReservation.Phone = telephoneNumberBox.Text;
newReservation.PreferredMethod = contactDropDown.SelectedIndex.ToString();
if (singleKingButton.Checked)
{
newReservation.BedType = "Single King";
}
if (twoQueensButton.Checked)
{
newReservation.BedType = "Two Queens";
}
if (singleQueenButton.Checked)
{
newReservation.BedType = "Single Queen";
}
Session["Reservation"] = newReservation;
Response.Redirect("~/ConfirmationPage.aspx");
}
//When the clear button is clicked clear the form and reset fields to their default values
protected void clearButton_Click(object sender, EventArgs e)
{
arrivalDateBox.Text = DateTime.Today.ToShortDateString();
departureDateBox.Text = String.Empty;
peopleDropDown.SelectedIndex = 0;
singleKingButton.Checked = true;
twoQueensButton.Checked = false;
singleQueenButton.Checked = false;
specialRequestsBox.Text = String.Empty;
firstNameBox.Text = String.Empty;
lastNameBox.Text = String.Empty;
addressBox.Text = String.Empty;
telephoneNumberBox.Text = String.Empty;
contactDropDown.SelectedIndex = 0;
}
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="garrettPenfieldUnit4.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Royal Inn and Suites</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/Main.css" rel="stylesheet" />
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server" defaultbutton="submitButton" defaultfocus="arrivalDateBox">
<div class="container">
<div id="page-header">
<h1 style="color: blue;">Royal Inn and Suites</h1>
<p style="color: red; font-style: italic;">
Where you're always treated like royalty
</div>
<h3 style="color: blue;">Reservation Request</h3>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />
</div>
<div id="form-group">
<h4>Request Data</h4>
<div>
Arrival Date<asp:RequiredFieldValidator ID="arrivalDateBoxValidator" runat="server" ErrorMessage="Arrival date is required"
ControlToValidate="arrivalDateBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="arrivalDateValidator" runat="server" ErrorMessage="Arrival date must be before departure date."
ControlToValidate="arrivalDateBox" ControlToCompare="departureDateBox" Display="Dynamic"
Operator="DataTypeCheck" Type="Date" ForeColor="red">*</asp:CompareValidator>
</div>
<div>
<asp:TextBox ID="arrivalDateBox" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div>Departure Date</div>
<div>
<asp:TextBox ID="departureDateBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="departureDateBoxValidator" runat="server" ErrorMessage="Departure date is required"
ControlToValidate="departureDateBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="departureDateCompareValidator" runat="server" ErrorMessage="Departure date must be after arrival date"
ControlToValidate="departureDateBox" ForeColor="Red" ControlToCompare="arrivalDateBox" Display="Dynamic" Operator="GreaterThan"
Type="Date">*</asp:CompareValidator>
</div>
<div>Number of People</div>
<div>
<asp:DropDownList ID="peopleDropDown" runat="server" CssClass="form-control">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<div>
Bed Type
<asp:RadioButton ID="singleKingButton" runat="server" Text="King" GroupName="bedType" />
<asp:RadioButton ID="twoQueensButton" runat="server" Text="Two Queens" GroupName="bedType" />
<asp:RadioButton ID="singleQueenButton" runat="server" Text="Single Queen" GroupName="bedType" />
</div>
</div>
<h3>Special Requests</h3>
<div>
<asp:TextBox ID="specialRequestsBox" runat="server" TextMode="MultiLine" CssClass="form-control"></asp:TextBox>
</div>
<h3>Contact Information</h3>
<div>First Name</div>
<asp:TextBox ID="firstNameBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="firstNameBoxValidator" runat="server" ErrorMessage="First name is required"
ControlToValidate="firstNameBox" ForeColor="Red">*</asp:RequiredFieldValidator>
<div>Last Name</div>
<asp:TextBox ID="lastNameBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="lastNameBoxValidator" runat="server" ErrorMessage="Last name is required"
ControlToValidate="lastNameBox" ForeColor="Red">*</asp:RequiredFieldValidator>
<div>E-mail Address</div>
<asp:TextBox ID="addressBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="addressBoxValidator" runat="server" ErrorMessage="Email address is required"
ControlToValidate="addressBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="addressBoxExpressionValidator1" runat="server" ErrorMessage="Invalid Email"
ControlToValidate="addressBox" ForeColor="Red" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
<div>Telephone Number</div>
<asp:TextBox ID="telephoneNumberBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="telephoneNumberBoxValidator" runat="server" ErrorMessage="Telephone Number is required"
ControlToValidate="telephoneNumberBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="telephoneExpressionValidator" runat="server"
ErrorMessage="Invalid phone number" ControlToValidate="telephoneNumberBox" ForeColor="red" Display="Dynamic" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">*</asp:RegularExpressionValidator>
<div>Preferred Method of Contact</div>
<asp:DropDownList ID="contactDropDown" runat="server" CssClass="form-control">
<asp:ListItem>E-mail</asp:ListItem>
<asp:ListItem>Telephone</asp:ListItem>
</asp:DropDownList>
<div>
<asp:Button ID="submitButton" class="btn btn-primary btn-space" runat="server" Text="Submit" OnClick="submitButton_Click" />
<asp:Button ID="clearButton" class="btn btn-primary btn-space" runat="server" Text="Clear" OnClick="clearButton_Click" BackColor="#33CC33" />
</div>
<div>
<asp:Label ID="submitLabel1" runat="server" Text="Thank you for your Request." Visible="False" ForeColor="Green"></asp:Label>
</div>
<div>
<asp:Label ID="submitLabel2" runat="server" EnableViewState="False" Text="We will get back to you within 24 hours." Visible="False" ForeColor="Green"></asp:Label>
</div>
</div>
</form>
</body>
</html>
One of these all properties is receiving 'NULL' and at the time of inserting this values in database your table structure is not allowing 'NULL'.
So make sure that if you want to store 'NULL' in table then allow NULL in table structure (Table design).
You can check it using "line by line execution" of your code (using break point).

CustomValidator Error Message not showing up in ValidationSummary

I'm kind of baffled. Can someone help me point out why my validation summary is not showing the custom validators? When I step through the code in the custom validators the args.IsValid is set to false.
<asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="alert alert-danger" DisplayMode="List" ShowSummary="true" ValidationGroup="ValidateUser" />
<fieldset class="form-horizontal">
<legend><asp:Literal runat="server" ID="litFirstName" /> <asp:Literal runat="server" ID="litLastName" /><asp:Literal runat="server" id="litLockedBadge" /></legend> <div class="control-group">
<label class="control-label" for="inputEmail">
<asp:CustomValidator ID="cvEmailAddress" runat="server" ValidationGroup="ValidateUser" Text="*" CssClass="required" ControlToValidate="txtEmailAddress" Display="Dynamic" OnServerValidate="cvValidateEmail" />
<asp:RequiredFieldValidator runat="server" CssClass="required" Display="Dynamic" ControlToValidate="txtEmailAddress" Text="*" ErrorMessage="Email Address Required" ValidationGroup="ValidateUser" /> Email Address</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtEmailAddress" ClientIDMode="Static" CssClass="span3" />
</div>
</div>
<div class="control-group input-append">
<label class="control-label" for="txtUserName"><asp:CustomValidator runat="server" ID="cvUserName" Text="*" CssClass="required" Display="Dynamic" OnServerValidate="cvValidateUserName" ValidationGroup="ValidateUser" /><asp:RequiredFieldValidator runat="server" Display="Dynamic" CssClass="required" ControlToValidate="txtUserName" Text="*" ErrorMessage="Username Required" ValidationGroup="ValidateUser" /> Username</label>
<div class="controls">
<asp:Textbox Text="test" runat="server" id="txtUserName" ClientIDMode="Static" CssClass="span3" />
<asp:LinkButton data-attr="email" ID="lnkEmailUsername" runat="server" CssClass="btn" OnClick="btn_ClickEmailUsername" ClientIDMode="Static"><i class="icon-envelope"></i></asp:LinkButton>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<div class="btn-group">
<asp:Button runat="server" ID="btnUnlockAccount" CssClass="btn" Text="Unlock Account" />
<asp:Button runat="server" ID="btnResetPassword" CssClass="btn" Text="Reset Password" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"></label>
<div class="controls">
<asp:Button runat="server" ID="btnSubmit" CssClass="btn btn-primary" Text="Update User Account" OnClick="btn_UpdateUserAccount" ValidationGroup="ValidateUser" />
</div>
</div>
</fieldset>
Here is the code behind
//Validate the Username
protected void cvValidateUserName(object source, ServerValidateEventArgs args)
{
string userName = txtUserName.Text;
cvUserName.ErrorMessage = "";
args.IsValid = true;
if (userName.Contains(" "))
{
cvUserName.ErrorMessage = "Username cannot contain spaces. ";
cvUserName.IsValid = false;
}
if (userName.Length > 100 || userName.Length < 8)
{
cvUserName.ErrorMessage += "Username must be between 8 and 100 characters. ";
cvUserName.IsValid = false;
return;
}
}
//Validate Email Address
protected void cvValidateEmail(object source, ServerValidateEventArgs args)
{
var emailAddress = txtEmailAddress.Text;
try
{
new MailAddress(emailAddress);
}
catch (Exception)
{
args.IsValid = false;
return;
}
}
In order for the Validator's error message to display in the ValidationSummary, you need to set the Validators Display="none". I also set Text="".

User is creating when email is in wrong format even though I used the regualr expression validator

I am trying to create a user with the create user wizard. For email validation i am using regualr expression control. I given ControlToValidate property to the id of the email text box. When I given wrong email Id and click on create user it is showing error message what i configured in the <asp:RegularExpressionValidator>but it is going to next step and saying user created succesfully. How to stop register the user when email format is wrong. I am trying to modify the CreatingUser event like this
protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
{
bool allfieldsstatus = false;
RegularExpressionValidator emailvalidator = (RegularExpressionValidator)CreateUserWizardStep1.ContentTemplateContainer.FindControl("emailvalidator");
if (!emailvalidator.Visible)
{
allfieldsstatus = true;
}
if (allfieldsstatus)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
But this is not working. The visibility property not at all showing. I tried in another way in if condition as
if(!emailvalidator.ErrorMessage.length!=0)
{
allfieldstatus = true;
}
This is also not working. Because the ErrorMessage property is always be there in configuration of <asp:RegularExpressionValidator >
What is the solution for this?
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
CssClass="createUseWizard" AutoGeneratePassword="True" ContinueDestinationPageUrl="~/Account/AdminRegister.aspx"
CreateUserButtonText="Register User"
OnCreatedUser="CreateUserWizard1_CreatedUser" BorderStyle="None"
DisplayCancelButton="True" oncreatinguser="CreateUserWizard1_CreatingUser"
LoginCreatedUser="False">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
<div id="registerUserDiv">
<div id="registerUserHeader">
Register New User
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="UserNameLabel" runat="server" Text="User Name" AssociatedControlID="UserName"></asp:Label>
</div>
<div class="inputTextbox">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator CssClass="showInRed" ID="UserIDrequired" runat="server" ControlToValidate="UserName"
ErrorMessage="Email is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1"
SetFocusOnError="True">*</asp:RequiredFieldValidator>
</div>
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="Label1" runat="server" Text="E-mail" AssociatedControlID="Email"></asp:Label></div>
</div>
<div class="inputTextbox">
<asp:TextBox ID="Email" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator CssClass="showInRed" ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required."
ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="Label2" Text="Select Role" runat="server" />
</div>
<div class="inputTextbox">
<asp:DropDownList ID="rolesDropdown" runat="server">
</asp:DropDownList>
</div>
</div>
<div>
<div class="errorEmail">
<asp:RegularExpressionValidator ID="emailvalidator" runat="server"
ErrorMessage="Email Should be in correct format" ControlToValidate="Email"
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic"></asp:RegularExpressionValidator>
</div>
</div>
<div>
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</div>
</div>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
In general, you should check if validation passed with the IsValid property of single validator controls or of the Page itself:
if (!emailvalidator.IsValid) {
e.Cancel = true;
}
or
if (!Page.IsValid) {
e.Cancel = true;
}
For the wizard, you could perform this check in the NextButtonClick and FinishButtonClick event handlers.
If you think it's RegExp problem try this:
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i

Recaptcha not working in asp.net application

I'm trying to user recaptcha control in my application. For some reason it's all the time valid. no matter what values I put in recaptcha field it's all the time valid. Any idea what I'm missing?
here is my code
<%# Control Language="C#" CodeBehind="RegisterControl.ascx.cs" AutoEventWireup="true"
Inherits="UserControls.RegisterControl" %>
<%# Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>
<asp:Panel ID="PlReg" runat="server" DefaultButton="CreateUserButton">
<div class="Reg_Wrapper">
<span class="failureNotification">
<asp:Literal ID="ErrorMessage" runat="server"></asp:Literal>
</span>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtUserName" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="UserNameRequired" runat="server"
ControlToValidate="TxtUserName" CssClass="failureNotification" ErrorMessage="User Name is required."
ToolTip="User Name is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtEmail" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="EmailRequired" runat="server" ControlToValidate="TxtEmail"
CssClass="failureNotification" ErrorMessage="E-mail is required." ToolTip="E-mail is required."
ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RevEmail" ControlToValidate="TxtEmail" runat="server"
ErrorMessage="*" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">
<img src="/Images/required.png" alt="Required" />
</asp:RegularExpressionValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtPassword" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator Display="Dynamic" ID="PasswordRequired" runat="server"
ControlToValidate="TxtPassword" CssClass="failureNotification" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
<asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Conf. Password:</asp:Label></div>
<div class="Reg_Control">
<asp:TextBox ID="TxtConfirmPassword" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="TxtConfirmPassword" CssClass="failureNotification"
Display="Dynamic" ErrorMessage="Confirm Password is required." ID="ConfirmPasswordRequired"
runat="server" ToolTip="Confirm Password is required." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:RequiredFieldValidator>
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="TxtPassword"
ControlToValidate="TxtConfirmPassword" CssClass="failureNotification" Display="Dynamic"
ErrorMessage="The Password and Confirmation Password must match." ValidationGroup="RegisterUserValidationGroup"><img src="/Images/required.png" alt="Required" /></asp:CompareValidator>
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
</div>
<div class="Reg_Control">
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" PublicKey="my public key"
PrivateKey="my private key" Theme="white" />
</div>
<div class="Clear">
</div>
<div class="Reg_ControlName">
</div>
<div class="Reg_Control">
<asp:Button ID="CreateUserButton" role="button" runat="server" CommandName="MoveNext"
Text="Create User" ValidationGroup="RegisterUserValidationGroup" CssClass="Reg_Button"
OnClick="CreateUserButton_Click" /></div>
<div class="Clear">
</div>
</div>
</asp:Panel>
serverside
protected void CreateUserButton_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
ErrorMessage.Text = "page is valid";
}
else
{
ErrorMessage.Text = "page is not valid";
}
}
Here's one that works for me. Be sure to insert correct keys on server:
<recaptcha:RecaptchaControl ID="recaptcha" Theme="clean" runat="server"
PublicKey="hiddenxxx" TabIndex="7" ToolTip="Accessible CAPTCHA"
privateKey="hiddenxxx" />
<asp:Label CssClass="captchaLabel" ID="lblResult" runat="server" />
As you can see, I usually keep the CAPTCHA error message separate from the other messages.
Code-behind:
if(Page.IsValid)
{
...
}
else
{
lblResult.Text = "Incorrect!";
lblResult.ForeColor = System.Drawing.Color.Red;
}
i dont think check captcha validation out on page load there should be submit button that you have and you check it out in click event of the button, this is how i use. i think you should check links blove...
http://code.google.com/intl/tr-TR/apis/recaptcha/docs/aspnet.html
http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx

Categories

Resources