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; }
Related
I am using CustomValidator for Telerik RadMaskedTextbox.The problem is that if i don't put any value , it doesn't show errormessage.
<telerik:RadMaskedTextBox ID="RadMaskedTextBox3" runat="server"
Width="150"
Mask="(###) ###-#### ext. #####">
</telerik:RadMaskedTextBox>
<asp:CustomValidator ID="CustomValidator4" runat="server"
ErrorMessage="*"
Display="Dynamic"
CssClass="error1"
Enabled="false"
ToolTip="At least one Phone no: needs to be filled in."
ValidateEmptyText="true"
EnableClientScript="true"
OnServerValidate="CustomValidator_ServerValidate"
SetFocusOnError ="true"
ValidationGroup="CarrierBaseInformation1">
</asp:CustomValidator>
Here you are another example with a CustomValidator:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="CheckLength"
ErrorMessage="Phone\Fax numbers must be 7 or 9 digits"
ControlToValidate="txtTollFree">*</asp:CustomValidator>
<script>
function CheckLength(source, args)
{
if (args.Value.length == 10 || args.Value.length == 13)
{
args.IsValid = true;
}else{
args.IsValid = false;
}
}
</script>
Here is an example how to achieve your goal:
In the Web.config set
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>
In the aspx
<telerik:RadMaskedTextBox Mask="(###) ###-#### ext. #####" RenderMode="Lightweight" ID="RadMaskedTextBox1" runat="server" EmptyMessage="Enter username"></telerik:RadMaskedTextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ControlToValidate="RadMaskedTextBox1"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="PostBack" />
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 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>
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 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.