In my web form I have 2 field that should only accept number (the calculation result of their value should shown in the third field. The RegularValidation of those two fields works fine before user click submit button. but NOT after. How to handle it?
<asp:TextBox ID="TextBox1" runat="server" placeholder="Liter"></asp:TextBox><span style="color:red;font-weight:bold"> *</span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This is required" ForeColor="Red" ValidationGroup="test" ControlToValidate="TextBox1" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" ControlToValidate="TextBox1" runat="server" ForeColor="red" ErrorMessage="Enter only numbers!" ValidationExpression="\d+" Display ="Dynamic"></asp:RegularExpressionValidator>
The submit button:
protected void btn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) * 4.18 * Convert.ToInt32(TextBox2.Text)) / 3600).ToString();
double result = Convert.ToDouble(TextBox3.Text);
TextBox3.Text = String.Format("{0:0.00}", result);
you can write a function / method like this to pass the value of the TextBox
public static bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Int32 result;
return Int32.TryParse(val, NumberStyle,
System.Globalization.CultureInfo.CurrentCulture, out result);
}
Call and check the method for example passing the following
var _isNumeric2 = isNumeric("9.", System.Globalization.NumberStyles.Integer);
Replace the first paramtere with the TextBox3.Text value
All was needed is to add ValidationGroup="test" same as the field. The solution is:
<asp:TextBox ID="TextBox1" runat="server" placeholder="Liter"></asp:TextBox><span style="color:red;font-weight:bold"> *</span>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This is required" ForeColor="Red" ValidationGroup="test" ControlToValidate="TextBox1" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" ControlToValidate="TextBox1" runat="server" ForeColor="red" ErrorMessage="Enter only numbers!" ValidationExpression="\d+" ValidationGroup="test" Display ="Dynamic"></asp:RegularExpressionValidator>
Related
I have multiple validators on the page that all work properly when the Submit button is clicked
However, I need to check if the validators have failed when I initiate a postback through a dropdown selected index changed event so that the failed validation messages properly persist stay
In other words I am trying to check if the certain validator has been just fired and failed
I tried the following
I checked the isValid property, but it is always true no matter what
I tried to check Page.IsValid method but it fails without the previous
Page.Validate() call
I tried to check if the failed message is visible and present but there no
such option for the validator
Thus, is there a way to check if the required validator was just fired and failed?
It seems to be something simple but I still can't find a solution
Thank you very much in advance
Came up with a solution
HTML
<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate>
<table class="innerTable" border="0">
<tr>
<td>
<asp:DropDownList CssClass="textboxwidth" runat="server" ID="ddOrg" AutoPostBack="true" OnSelectedIndexChanged="ddOrg_SelectedIndexChanged" setCausesValidation="true"></asp:DropDownList>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator3" runat="server" Display="Dynamic" ControlToValidate="ddOrg" InitialValue="" ErrorMessage="* Required"></asp:RequiredFieldValidator>
<input type="hidden" id="hdFirmValidator" runat="server" />
<input type="hidden" id="hdPhoneValidator" runat="server" />
<input type="hidden" id="hdPhoneValidatorRegex" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOrgOther" Enabled="false" CssClass="textboxwidth" MaxLength="100" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator12" Enabled="false" runat="server" Display="Dynamic" ControlToValidate="txtOrgOther" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox CssClass="textboxwidth" ID="txtOrgAddress" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator14" runat="server" Display="Dynamic" ControlToValidate="txtOrgAddress" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox CssClass="textboxwidth" ID="txtOrgPhone" runat="server" MaxLength="30"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator15" runat="server" Display="Dynamic" ControlToValidate="txtOrgPhone" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPhone1" ValidationExpression="^.{0,30}" ErrorMessage="*Enter upto 30 digit phone number" runat="server" ControlToValidate="txtOrgPhone"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
</ContentTemplate>
JavaScript
window.onload = function () {
var btnSubmit = document.getElementById("<%=btnSubmit.ClientID%>");
function SetHiddenFields() {
var firmValidator = document.getElementById("<%=RequiredFieldValidator14.ClientID%>");
var hdFirmValidator = document.getElementById("<%=hdFirmValidator.ClientID%>");
hdFirmValidator.value = firmValidator.style.display;
var phoneValidator = document.getElementById("<%=RequiredFieldValidator15.ClientID%>");
var hdPhoneValidator = document.getElementById("<%=hdPhoneValidator.ClientID%>");
hdPhoneValidator.value = phoneValidator.style.display;
var phoneValidatorRegEx = document.getElementById("<%=regexPhone1.ClientID%>");
var hdPhoneValidatorRegex = document.getElementById("<%=hdPhoneValidatorRegex.ClientID%>");
hdPhoneValidatorRegex.value = phoneValidatorRegEx.style.display;
return true;
}
btnSubmit.onclick = SetHiddenFields; }
Codebehind
protected void ddOrg_SelectedIndexChanged(object sender, EventArgs e)
{
//Srver side code
RequiredFieldValidator3.Validate();
if (hdFirmValidator.Value != string.Empty)
{
RequiredFieldValidator14.Validate();
}
if (hdPhoneValidator.Value != string.Empty)
{
RequiredFieldValidator15.Validate();
}
if (hdPhoneValidatorRegex.Value != string.Empty)
{
regexPhone1.Validate();
}
}
My code is like this
<asp:TextBox ID="txtStartDate" CssClass="txtStartDate" runat="server" MaxLength="10" />
<asp:RequiredFieldValidator ID="startDateRequiredFieldValidator" runat="server" ValidationGroup="Dates" ControlToValidate="txtStartDate"
EnableClientScript="True" Display="None" Text="*" ErrorMessage="Start date is required."/>
<asp:CompareValidator ForeColor="Red" id="startDateCompareValidator1" runat="server" Type="Date"
ValidationGroup="Dates" Display="None" EnableClientScript="True"
Operator="DataTypeCheck" ControlToValidate="txtStartDate" Text="*"
ErrorMessage="Start date is not valid or is in an incorrect format. Please use the format yyyy-MM-dd."/>
<asp:RangeValidator id="ReturnDateRangeValidator" runat="server" ControlToValidate="txtStartDate" ValidationGroup="Dates"
MinimumValue="2005-01-01" MaximumValue="2050-01-01" Display="None" EnableClientScript="True" Text="*"
ErrorMessage="Start date is too far back in time or it is to far in future, please enter a more feasible date."/>
<cc1:CalendarExtender ID="Calendarextender2" runat="server" Format="yyyy-MM-dd" PopupButtonID="Image2"
TargetControlID="txtStartDate" FirstDayOfWeek="Monday">
</cc1:CalendarExtender>
I have a date field and I can use delete,backspace into IE but I can't do it into Chrome. My question is how can I enable backspace,delete into Chrome . Any info will be helpful regarding this
You Can Use JQuery For this
here is your textbox with event keypress
<asp:TextBox ID="txtStartDate" CssClass="txtStartDate" onkeypress="return allowBackSpace(this);" runat="server" MaxLength="10" />
Some Script
function allowBackSpace(val) {
var keyCodeEntered = (event.which) ?
event.which :
(window.event.keyCode) ?
window.event.keyCode :
-1;
if (keyCodeEntered == 8) {
$(this).val("");
return false;
}
return false;
}
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.
I am designing a web-application using asp.net with c# and I just added a validation code for a textbox,it seems like it is good enough to execute,but no validation issues is been shown when the application is executed when input is null or invalid.
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" DisplayMode="BulletList"
HeaderText="Validation issues" ShowSummary="False" ValidationGroup="Validation"/>
<asp:TextBox ID="txtrandom" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Enter the Randomly generated numbers"
ControlToValidate="txtrandom" Display="None"
ValidationGroup="Validation" SetFocusOnError="true" >
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2"
runat="server" ErrorMessage="Input should be in number"
ValidationExpression="^[0-9]+$"
ControlToValidate="txtrandom"
Display="None"
ValidationGroup="Validation"
SetFocusOnError="true" >
</asp:RegularExpressionValidator>
In the backend(c#) I have these line of code
int random = 0;
bool isValidInt = int.TryParse(txtrandom.Text, out random);
for (int i = 0; i < random; i++)
{
//other codes
}
Does these lines of code effect the validation or just a syntactical error? Any help is appreciated.As far as i know he text box is taking 0 as a default value.
The problem is with the validation group . If you are not using the validation group everything will work but if you specified a validation group then the group has to be enabled in the button click event or something similar.
see my code . it is working fine.
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" DisplayMode="BulletList"
HeaderText="Validation issues" ShowSummary="false" ValidationGroup="one" />
<asp:TextBox ID="txtrandom" runat="server" ></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Enter the Randomly generated numbers" Display="None"
ControlToValidate="txtrandom" ValidationGroup="one" >
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2"
runat="server" ErrorMessage="Input should be in number"
ValidationExpression="^[0-9]+$"
ControlToValidate="txtrandom"
Display="None"
ValidationGroup="one"
SetFocusOnError="true" >
</asp:RegularExpressionValidator>
<asp:Button ID="test" runat="server" Text="Submit" ValidationGroup="one" />
</div>
and yes validation group can be invoked on the post back.So error message wont display onfocouschange just like the normal validation.
Assign Validation group to textbox like this:
<asp:TextBox ID="txtrandom" runat="server" ValidationGroup="Validation"></asp:TextBox>
You can Try this Code, I am also using this code of numeric checking
bool isnum;
double numericval;
isnum = double.TryParse(numval, out numericval);
if (isnum)
{ return true; }
else { return false; }
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.. ....
}