Range Validator - alphabet entered when integer range checked - asp.net

I have a Range Validator as follows. It is for restricting values between 1900 and 2070. However, it fires error when I enter a alphabet also. I want this to be fired only if the user enters integer values. How do I overcome it? Please help..
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtYear"
ValidationGroup="report" ErrorMessage="EM1|Year" MaximumValue="2079" MinimumValue="1900"
SetFocusOnError="True" Display="Dynamic" Type="Integer">
<img src="../../Images/error.gif" alt="Format" />
</asp:RangeValidator>

You can use custom validator in this case.
It may look like this
Use this as your validator code -
<asp:customvalidator ID="Customvalidator1" ControlToValidate="txtYear" runat="server"
EnableClientScript="true"
errormessage="CustomValidator"
onservervalidate="Customvalidator1_ServerValidate"></asp:customvalidator>
Use this in your code behind -
protected void Customvalidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int result;
if (int.TryParse(txtYear.Text,out result))
{
if (1900 <= result && result <= 2079)
args.IsValid = true;
else
args.IsValid = false;
}
args.IsValid = true;
}

Related

CustomValidator doesnt display a message unless I use a validation summary

I want to output a message in case if an invalid date was supplied.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
DateTime temp;
if (DateTime.TryParse(args.Value, out temp))
{
args.IsValid =true;
}
else
{
args.IsValid = false;
}
}
catch (Exception ex)
{
args.IsValid = false;
}
}
I expect the output message to be located near the field.
Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.
Is there away display the message without the validation summary?
Is there away display the message without the validation summary?
You will need to use Text attribute instead of ErrorMessage.
<asp:CustomValidator ID="CustomValidator1"
ControlToValidate="RegistrationFromTextBox2"
OnServerValidate="CustomValidator1_ServerValidate"
ValidationGroup="NewMailingItem"
runat="server"
Text="The date is invalid">
</asp:CustomValidator>
FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"
placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
ID="RegistrationFromCompareValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="RegistrationFromTextBox2"
Text="The date is invalid">
</asp:CompareValidator>

ASP.Net Custom Validator failed ,form gets submitted

I have made a form in which there are two RAD DateTimePicker Controls . One is for Start-DateTime and other is for End Date Time. Inside Custom Validator, I have Compared the Date Time Picked So far and hence made it valid or invalid accordingly its Server Validate event code goes like this.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Its Design Code goes like this.
<telerik:RadDateTimePicker ID="rdpStartDate" runat="server" AutoPostBackControl="Both" onselecteddatechanged="rdpStartDate_SelectedDateChanged">
<TimeView CellSpacing="-1" Culture="en-IN">
</TimeView>
<TimePopupButton HoverImageUrl="" ImageUrl="" />
<Calendar UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x">
</Calendar>
<DateInput AutoPostBack="True" DateFormat="dd-MM-yyyy" DisplayDateFormat="dd-MM-yyyy">
</DateInput>
<DatePopupButton HoverImageUrl="" ImageUrl="" />
</telerik:RadDateTimePicker>
<asp:Label ID="Label2" runat="server" Text=" To" CssClass="h_text"></asp:Label>
<telerik:RadDateTimePicker ID="rdpEndDate" runat="server" onselecteddatechanged="rdpEndDate_SelectedDateChanged" AutoPostBackControl="Both">
<TimeView CellSpacing="-1" Culture="en-IN"></TimeView>
<TimePopupButton ImageUrl="" HoverImageUrl=""></TimePopupButton>
<Calendar UseRowHeadersAsSelectors="False" UseColumnHeadersAsSelectors="False" ViewSelectorText="x"></Calendar>
<DateInput DisplayDateFormat="dd-MM-yyyy" DateFormat="dd-MM-yyyy" AutoPostBack="True"></DateInput>
<DatePopupButton ImageUrl="" HoverImageUrl=""></DatePopupButton>
</telerik:RadDateTimePicker>
Validator Source Code in designer is like this.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
I want to ask that even when custom validator fails, My form gets submitted with faulty values. What can be the reason? How can I avoid that?
With Server validator Event like:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) {
if (rdpEndDate.SelectedDate < rdpStartDate.SelectedDate) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
You have to check on your server event as well like:(For example if you are using your validator with button click then)
protected void btn_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Write("Page is valid.");
}
else
{
Response.Write("Page is not valid!");
}
}
My suggestion: Telerik has a good client side support as well so I suggest you to use client side validation of custom validator.
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="rdpEndDate"
ErrorMessage="End Date Cant be Before Start Date"
ClientValidationFunction="CheckDates"
SetFocusOnError="True"
ValidateEmptyText="True" ValidationGroup="submit">End Date Cant be Before Start Date</asp:CustomValidator>
then in Javascript:
function CheckDates(sender, args)
{
var cltRdpEndDate= $find("<%=rdpEndDate.ClientID %>");
var cltRdpStartDate= $find("<%=rdpStartDate.ClientID %>");
if(cltRdpEndDate.get_dateInput().get_selectedDate()< cltRdpStartDate.get_dateInput().get_selectedDate())//if your condtion fails here
{
args.IsValid = false;
return;
}
args.IsValid = true;
}

How can I cast a Text attribute to an integer for a RangeValidator using ASP.Net?

I'm obviously new to ASP.Net, but I have a quick question.
I have text boxes and labels for forms on the main page. One of the text boxes is a wager amount. But since the input is a text box, I keep getting errors when trying to pass one of the other text box ID's (stake) to the RangeValidator.
To clear that up.. I need the RangeValidator for wager to be between 1 and stake. Since obviously a wager can't be more than the stake.
I tried using CInt(currentstake.Text) and some other things, but it seems like it's stuck as a string/text type.
Here's an example of what I've been trying to do:
<asp:RangeValidator ID="RangeValidator2" ControlToValidate="wager" ForeColor="Red" ErrorMessage="Please enter a valid wager." MinimumValue="1" MaximumValue="CInt(currentstake.Text)" Type="Integer" runat="server"></asp:RangeValidator>
Any easy way to fix this? Thanks!
I would use a CustomValidator which is the most flexible validator type. Here's a complete sample with a client- and servervalidation function incl. validation-groups:
aspx:
<asp:TextBox ID="Wager" runat="server" ValidationGroup="WagerVG"></asp:TextBox>
<asp:TextBox ID="Stake" runat="server" ValidationGroup="WagerVG"></asp:TextBox>
<asp:CustomValidator ValidationGroup="WagerVG" ID="CustomValidator1" runat="server"
OnServerValidate="WagerValidation"
ClientValidationFunction="WagerValidation_CV"
ValidateEmptyText="true"
ErrorMessage="Please enter a valid wager."
ForeColor="Red">
</asp:CustomValidator>
<asp:Button ID="SubmitWager" Text="Submit" ValidationGroup="WagerVG" runat="server" />
javascript validation:
<script type="text/javascript">
function WagerValidation_CV(sender, e) {
var valid = false;
var txtWager = document.getElementById('<%= Wager.ClientID %>');
var txtStake = document.getElementById('<%= Stake.ClientID %>');
if (txtWager != null && txtStake != null) {
var wager = parseInt(txtWager.value);
var stake = parseInt(txtStake.value);
valid = wager >= 1 && wager <= stake;
}
e.IsValid = valid;
}
</script>
servervalidation-function:
protected void WagerValidation(object source, ServerValidateEventArgs args)
{
bool valid = true;
int wager, stake;
if (!int.TryParse(Wager.Text, out wager))
valid = false;
if (!int.TryParse(Stake.Text, out stake))
valid = false;
valid = valid && wager >= 1 && wager <= stake;
args.IsValid = valid;
}
A CustomValidator is typically used if multiple controls are dependent of each other. Remember to set ValidateEmptyText="true" to force validation even with empty textboxes and to omit the ControlToValidate to force validation on both controls.
Edit: another option is to use a combination of two CompareValidators and two RequiredFieldValidators(if you want to prevent empty texts):
<asp:CompareValidator ID="CompareValidator1" runat="server" ForeColor="Red" ValidationGroup="WagerVG"
ControlToValidate="Wager" ControlToCompare="Stake"
Operator="LessThanEqual" Type="Integer"
ErrorMessage="Please enter a value greater 0 and less or equal stake">
</asp:CompareValidator>
<asp:CompareValidator ID="CompareValidator2" runat="server" ForeColor="Red" ValidationGroup="WagerVG"
ControlToValidate="Wager" ValueToCompare="1"
Operator="GreaterThanEqual" Type="Integer"
ErrorMessage="Please enter a value greater 0 and less or equal stake">
</asp:CompareValidator>
One way to achieve this is using CustomValidation you can create a custom function javascript or in the server that check if the value is correct, so you can see this article for more information
Other option si to use an CompareValidator but doesn't work for range, you could also validate that the value is less than currentstake. So:
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToCompare="currentstake"
ControlToValidate="wager"
Operator="LessThan"
ErrorMessage="Wrong Value"
SetFocusOnError="True">

Regular expression for maximum digits excluding comma

I have the below regular expression:
ValidationExpression="[0-9]+(,[0-9]+)*"
It allows numbers in the format: 12,2345 or 231,23454
Now I want to include a condition that will on the whole allow only 7 digits max excluding
comma.
The below is the modified code
The below is in the item template
I also have a radio button in item template
<asp:TextBox runat="server" ID="tbText" CssClass="someclass" MaxLength="11"
%>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationExpression="[0-9]+(,[0-9]+)*" ID="ValComp" runat="server" CssClass="asdf"
ControlToValidate="tbMileage" Text="*" Enabled="false" Display="Dynamic"/>
<asp:CustomValidator ID="cvalMileage" runat="server" CssClass="adsf" Text="*" Display="Dynamic">
</asp:CustomValidator>
<asp:CustomValidator ID="CustomValidator1" ClientValidationFunction="functionName"
runat="server" CssClass="asd" Text="*" Display="Dynamic">
</asp:CustomValidator>
Since I want to validate the radio button checked corresponding textbox in repeater the below is the code I have written
var selText = $(".Class1 input[type=radio]:checked").closest(".Class1").find(".subClassText input[type=text]").val();
alert('Hi');
if (selText.replace(",", "").length <= 7) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
The alert fires twice and based on args is False i have a popup that is firing twice
Thanks.
Regular expressions are not good at this problem, but if you limit your input to a maximum of one comma this expression will fit:
([0-9]{0,0}[,]?[0-9]{0,7})|([0-9]{0,1}[,]?[0-9]{0,6})|([0-9]{0,2}[,]?[0-9]{0,5})|([0-9]{0,3}[,]?[0-9]{0,4})|([0-9]{0,4}[,]?[0-9]{0,3})|([0-9]{0,5}[,]?[0-9]{0,2})|([0-9]{0,6}[,]?[0-9]{0,1})|([0-9]{0,7}[,]?[0-9]{0,0})
You will recognize that this problem is not well suited for regular expression as this expression is fixed to your maximum of 7.
You could use a CustomValidator control with client-side validation like this:
ASPX code:
<asp:CustomValidator id="CustomValidator1" runat="server"
ControlToValidate="YourControlNameHere"
ClientValidationFunction="ClientValidation"
OnServerValidate="ServerValidation"
ErrorMessage="Invalid number." />
JavaScript (uses jQuery):
function ClientValidation(source, arguments)
{
var inputText = arguments.Value;
var expression = /^[0-9]+(,[0-9]+)*$/;
if (expression.test(inputText) && inputText.replace(",", "").length <= 7) {
arguments.IsValid = true;
}
else {
arguments.IsValid = false;
}
}
C# code behind:
public void ServerValidation(object source, ServerValidateEventArgs args)
{
string inputText = args.Value;
Regex regex = new Regex(#"^\d+(,\d+)*$");
if (regex.IsMatch(inputText) && inputText.Replace(",", "").Length <= 7)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

compare validator for DATE type

I want to compare 2 data in 2 textbox with DATE value,I used CompareValidator to compare them but it does not works for me how can I do? this is my CompareValidator code:
<asp:CompareValidator id="CompareValidator1"
runat="server" ErrorMessage="Invalid Date!" Type="Date"
ControlToValidate="SeconedDate_txt"
ControlToCompare="FirstDate_txt" Operator="GreaterThan"></asp:CompareValidator>
What format are you entering your dates in and what regional settings does your server have? Date comparison validation is Locale specific.
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid DateTime"
ControlToValidate="TextBox1"
OnServerValidate="CustomValidator1_ServerValidate">
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime tempDateTime;
String textDateTime = TextBox1.Text;
if (DateTime.TryParse(textDateTime, out tempDateTime))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
For this you will need ajax control toolkit, make sure you have downloaded the correct version for each .net framework.
<cc1:MaskedEditExtender ID="MaskedEditExtender5" runat="server" culturename="en-CA" mask="99/99/9999" masktype="Date" messagevalidatortip="true" argetcontrolid="txtEditExpireDate"></cc1:MaskedEditExtender>

Resources