I am working on a eCommerce project which has an admin panel and shopping panels.
I have finished programming and now testing every single aspx and cs files by manually.
The problem is, I have a change password feature which is related with session and Database. The problem is I have a validators in my aspx file but they won't work. Here my codes are;
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnChange">
<div class="userForm">
<div class="formTitle">
Change Your Password
</div>
<div class="formContent">
<asp:TextBox ID="txtPassword" placeholder="Type your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtPassword"
ErrorMessage="RequiredFieldValidator" ForeColor="Red" Display="Dynamic" ValidationGroup="signup">Enter a password</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="txtAgainPassword" placeholder="Repeat your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" BorderColor="Red"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Enter password again."
ForeColor="Red" ValidationGroup="signup"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Password don't match."
ForeColor="Red" ValidationGroup="signup"></asp:CompareValidator>
<br />
<asp:Button ID="btnChange" runat="server" Text="Submit" OnClick="btnChange_Click" />
<br />
<asp:Label ID="lblError" Visible="False" ForeColor="Green" runat="server"></asp:Label></div>
</div>
</asp:Panel>
</asp:Content>
and the .cs part is below
protected void btnChange_Click(object sender, EventArgs e)
{
using (ZirveMarketDBEntities context = new ZirveMarketDBEntities())
{
// Atanan sessiona gore user bilgisini al - guvenlik icin onemli
int id = (int)Session["CustomerID"];
Customer cust = context.Customers.Where(i => i.CustomerID == id).FirstOrDefault();
cust.Password = txtPassword.Text;
context.SaveChanges();
}
lblError.Visible = true;
lblError.Text = "Password successfully updated";
}
The problem is, I have a 2 box for new password and type new password. Even if they are null, even if they don't match the password still changes with the value of the first part. I don't want to run server side code if they don't match or null. What am I doing wrong? Helps are pretty apreciated.
Add the 'ValidationGroup="signup"' attribute to the btnChange button.
I'd also recommend adding the below to the click event (before anything else) in case Javascript is disabled on the client:
Page.Validate("signup");
if (!Page.IsValid)
{
return;
}
You have validation groups specified on the validators, but not on the Button. Try adding the validation group to the button as well.
Related
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");
}
}
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.
my idea is that when the user fills Username text box and goes to next textbox without refreshing page the enters username to be checks by database and if it was not empty and was available then in side of username textbox shows an available image and else shows the unavailable image.but the code that I have found is :
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">نام کاربری :</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" AutoPostBack="true" OnTextChanged="Username_Changed" size="23" class="field" runat="server"></asp:TextBox>
<br /> <div runat="server" visible="false" id="UserAvailability"></div> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="نام کاربری نمیتواند خالی باشد." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
the .cs code:
protected void Username_Changed(object sender, EventArgs e)
{
if (Membership.GetUser(UserName.Text) != null)
{
UserAvailability.InnerText = "this username is unavailable";
UserAvailability.Attributes.Add("class", "taken");
UserAvailability.Visible = true;
}
else
{
UserAvailability.InnerText = "username is available";
UserAvailability.Attributes.Add("class", "available");
UserAvailability.Visible = true;
}
}
how can I change these codes to be work by image whitout text?
Use the .innerHTML method of the DIV tag and this will allow you to use tags for your graphic instead of text message. Good luck
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
Im a newbie to the world of ASP and C#, I have just created my first Registration form using the CreateUserWizard Membership Provider and set up the validators which work great, Appart from the "Username". If the user name is taken the page simply refreshes and no error appears would be realy greatfull if somone could point out where I might be going wrong.
Here is my current code :
SCRIPT
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
/* User is created and setting extra parameters to profile */
TextBox UserNameTextBox = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
string username = UserNameTextBox.Text;
MembershipUser User = Membership.GetUser(username);
umbraco.cms.businesslogic.member.Member member = new umbraco.cms.businesslogic.member.Member((int)User.ProviderUserKey);
/* Here you can access properties for the member */
umbraco.cms.businesslogic.property.Property FullNameProperty = member.getProperty("fullname"); // Property alias
TextBox FullNameTextBox = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FullName");
FullNameProperty.Value = FullNameTextBox.Text;
Roles.AddUserToRole(CreateUserWizard1.UserName, "NuneatonMember");
}
protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)
{
Response.Redirect("/member-area.aspx");
}
CONTENT
<form runat="server">
<asp:CreateUserWizard ID="CreateUserWizard1" OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick" OnCreatedUser="CreateUserWizard1_CreatedUser" runat="server">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
First Name :<asp:TextBox Runat="server" ID="FullName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="FullNameVal" runat="server" ControlToValidate="FullName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Last Name :<asp:TextBox Runat="server" ID="LastName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="LastNameVal" runat="server" ControlToValidate="LastName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Username :<asp:TextBox Runat="server" ID="UserName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameVal" runat="server" ControlToValidate="UserName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
E-mail :<asp:TextBox Runat="server" ID="Email" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailVal" runat="server" ControlToValidate="Email" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="Email" ValidationExpression=".*#.*\..*" ErrorMessage="* is not a valid e-mail address." ValidationGroup="CreateUserWizard1" display="dynamic"></asp:RegularExpressionValidator>
<br/>
Password :<asp:TextBox Runat="server" ID="Password" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordVal" runat="server" ControlToValidate="Password" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Confirm Password :<asp:TextBox Runat="server" ID="ConfirmPassword" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="PConfirmVal" runat="server" ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" Display="Dynamic" ValidationGroup="CreateUserWizard1" ErrorMessage="Foul: Password and Confirmation Password do not match. Fix them."></asp:CompareValidator>
<asp:literal runat="server" enableviewstate="true" id="FailureText"></asp:literal>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"></asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
You need to add an error handler.
<asp:CreateUserWizard ID="CreateUserWizard1"
OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick"
OnCreatedUser="CreateUserWizard1_CreatedUser" runat="server"
OnCreateUserError="createUserWizard_CreateUserError">
And an example of how you could implement it.
protected void createUserWizard_CreateUserError(object sender, CreateUserErrorEventArgs arguments)
{
LogCreateUserError(arguments.CreateUserError, "no user info");
}
private void LogCreateUserError(MembershipCreateStatus status, string username)
{
string reasonText = status.ToString();
switch (status)
{
case MembershipCreateStatus.DuplicateEmail:
case MembershipCreateStatus.DuplicateProviderUserKey:
case MembershipCreateStatus.DuplicateUserName:
reasonText = "The user details you entered are already registered.";
break;
case MembershipCreateStatus.InvalidAnswer:
case MembershipCreateStatus.InvalidEmail:
case MembershipCreateStatus.InvalidProviderUserKey:
case MembershipCreateStatus.InvalidQuestion:
case MembershipCreateStatus.InvalidUserName:
case MembershipCreateStatus.InvalidPassword:
reasonText = string.Format("The {0} provided was invalid.", status.ToString().Substring(7));
break;
default:
reasonText = "Due to an unknown problem, we were not able to register you at this time";
break;
}
//DO whatever with it.. ....
}