RangeValidator currency validation makes no sense - asp.net

I'm having some issues using a RangeValidator in ASP.NET 4.5. The issue I'm facing is trying to validate a range of currency values.
Let's say I have the following RangeValidator:
<asp:RangeValidator ID="_rngValCustomAmount" runat="server"
CssClass="error-message" ErrorMessage="Please enter a valid amount."
ControlToValidate="_txtCustomAmount" MinimumValue="10.00"
MaximumValue="500.00" Type="Currency" />
When I enter a value of '450' the validation is passed, and I can submit the form. However, if I enter '$450' then the validation fails, even though I have set the Type property to Currency.
So, then I thought, OK, maybe I need to enter a currency Minimum and Maximum value, however when I change the control to:
MinimumValue="$10.00"
MaximumValue="$500.00"
I get the following .NET exception:
The value '$500.00' of the MaximumValue property of '_rngValCustomAmount' cannot be converted to type 'Currency'.
I don't really want to have to resort to using a CustomValidator for this, so that I don't have to write a JS function for something that should exist as the RangeValidator supports the currency type. Can anyone point out what I might be doing wrong?

Related

RegularExpressionValidator to limit input length and allow empty strings

I'm really bad with regex and was looking at another question almost identical to this but can't get it to work as I need.
I was to use a RegularExpressionValidator that will allow any character up to 255 characters or nothing at all. I tried,
ValidateExpression="^.{255}$"
but it throws an unhanded exception when the textbox that I'm checking is empty.
I've also tried
ValidateExpression="^.{,255}$"
Thank you
Rodney
Did you try ^.{0,255}$? Not sure what exception you are getting though.
EDIT: Also, if struggling with .Net regex, Regex Hero tester is a great help. I know there are other sites, but this one is by far the best, if you ask me.
The proper expression is ^.{0,255}$.
^.{255}$ will only match if there is exactly 255 characters, while ^.{,255}$ will match the literal string "{,255}".
If there are still issues after trying that, can you tell us the exception?
If it throws an HttpRequestValidationException exception, you can use the members of the UnvalidatedRequestValues class.
Mind that "Validation succeeds if the input control is empty" (MSDN). You may add a RequiredFieldValidator field to ensure that the user does not leave a text box blank (if you use the RequiredFieldValidator control inside an UpdatePanel control, make sure that the validator control and the control it is associated with are in the same panel - MSDN):
<asp:textbox id="myTB"
runat="Server">
</asp:textbox>
// ... MAKE SURE YOU DO NOT USE TextMode="Number"!!!
<asp:RequiredFieldValidator
ID="Value1RequiredValidator"
ControlToValidate="myTB"
ErrorMessage="Please enter a number.<br />"
Display="Dynamic"
runat="server"/>
And as for regex, ^.{255}$ means match any character (except newline) exactly 255 times between string start and end. I think it makes sense to allow ^[1-9][0-9]{0,254}$ (for values like '34', '104', etc.).

Intermittent error with CompareValidator - ValueToCompare property is ""

I have a page with a CompareValidator on it:
<asp:textbox id="txtResponseDate" runat="server" />
<asp:requiredfieldvalidator id="rfvResponseDate" runat="server"
controltovalidate="txtResponseDate"
display="Dynamic"
errormessage="Date is required."
setfocusonerror="true">
</asp:requiredfieldvalidator>
<asp:comparevalidator id="cmvDate" runat="server"
controltovalidate="txtResponseDate"
display="Dynamic"
errormessage="Date must not be before today."
operator="GreaterThanEqual"
setfocusonerror="true"
type="Date">
</asp:comparevalidator>
In the code behind, we set the ValueToCompare property like so:
If Not IsPostBack Then
cmvDate.ValueToCompare = DateTime.Now.ToString("d")
End If
Intermittently (we can't discern a pattern), we get the following error:
"The value '' of the ValueToCompare property of 'cmvDate' cannot be converted to type 'Date'."
With a call stack of:
at System.Web.UI.WebControls.CompareValidator.ControlPropertiesValid()
at System.Web.UI.WebControls.BaseValidator.get_PropertiesValid()
at System.Web.UI.WebControls.BaseValidator.Validate()
at System.Web.UI.Page.Validate()
at System.Web.UI.Page.Validate(String validationGroup)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
My first thought was something odd with the date format, but we're using UK dates, last error was on 18th July, so the ValueToCompare gets set to 18/07/2011. I've set this manually using the debugger, and it worked fine. Anybody any bright ideas as to why this may be happening?
I've checked the code - there is nowhere else that this is being set.
Using the debugger, I've double checked at postback, and as expected, this property value is retained.
The value '' of the ValueToCompare property of 'cmvDate' cannot be converted to type 'Date'.
This error message says, that in moment of validation property ValueToCompare of your rangeValidator itself (not the control you are validating) is not set. This can be if you wrote this lines:
If Not IsPostBack Then
cmvDate.ValueToCompare = DateTime.Now.ToString("d")
End If
not in Page_Init event.
Move the code of setting the ValueToCompare to the Init event, with removing the check for Postback.
Check, what value has this property during data check (may be, you should remove check for Not IsPostBack).
Set this property before check is occured.
In your control settings you set type="Date" whitch means that you will compare value as a DateTime object, but in the ValueToCompare property you set string object, not a DateTime.
If you need to compare by strings - set control setting type to String,
If you need to compare by dates - set DateTime object to the ValueToCompare control property and Operator="DataTypeCheck".
Are you getting any other ViewState-related errors? Like "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster."?
If so, maybe the problem is related to one of the things listed in this MS KB article: Intermittent Invalid Viewstate Error in ASP.NET Web pages.
There are several conditions that may cause this issue. Each known condition is presented with a short explanation and a possible workaround.
Application Pool Recycling
Server Farms or Server Clusters
Form Posts
Proxy servers and Virus Scanners
One other possible thing not mentioned in that article is a slow or unreliable connection along with resulting impatience of users. I worked on an app hosted in the US but many users are from India. We noticed a much greater frequency of these types of intermittent ViewState-related errors among the users in India. We speculated that it might have been because of higher latency, greater number of hops, lower bandwidth and users interacting with pages prior to page load completion.

only two digits allowed after decimal asp.net

I have a textbox where the user must not be able to enter more than two digits after a decimal.How do I do this without using javascript?
Thanks.
You can set the MaxLength property of the textbox, but that doesn't have any notion of whether or where the decimal point is.
You could also use a CustomValidator and check the inputted number on the server via the ServerValidate event. But this will require going to the server to check the value (i.e. it will initially look like your form allows users to input invalid numbers).
You should also be able use to a RegularExpressionValidator, depending on your exact globalization requirements, which will use JavaScript on the client to provide immediate feedback:
<asp:TextBox ID="NumberTextBox" runat="server" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="NumberTextBox"
ValidationExpression="\d+(?:(?:\.|,)\d{1,2})?" />
If you want the immediate feedback to the user, you'll need to use a JavaScript based solution.
You cannot cause the textbox to stop accepting text after two decimal places without directly or indirectly using javascript. (This is sometimes called an input mask).
You can, however, allow the user to enter free-form text and validate the text upon postback on the server. You can either automatically round the number for them, or return an error message to the client.
If you really need to prevent the user from entering more than two digits after the decimal point, you'll need to use JavaScript or a server control that implements the JavaScript for you.
However, may make more sense to allow them to enter any number of digits and then catch it on validation (or just round to two digits).

Why can't I validate values with the $ symbol in it?

I am using a CompareValidator to check user input on one of my forms but for some reason it will not allow me to enter a dollar sign.
According to MSDN the currency data type in the compare validator allows:
A decimal data type that can contain
currency symbols.
I am using the control below to validate:
<asp:CompareValidator ID="vld_Cash" runat="server" ControlToValidate="CashTextBox" Type="Currency" Operator="DataTypeCheck" ValidationGroup="vld_Update" ErrorMessage="The value entered for 'Cash' must be in a number format. Do NOT include dollar signs. Examples: 500 or 500.00" />
I also added the following to my web.config just to be sure:
<globalization culture="en-US" uiCulture="en-US"/>
But it still says any input with a $ in it is invalid. Am I missing something here?
The last comment in this thread shows why and gives you some ideas:
Currency Validator
An article dedicated to this:
ASP.Net: Validating a TextBox with a Dollar Sign (suggests using a RegularExpressionValidator).

RangeValidator Problem in ASP.NET

I was using RangeValidator to validate user input on client side for double values.
One of my user said that when he enters 5E-10, my range validator does not understand that number as a valid double.
What do you suggest me to do?
Thanks,
cas
This is a known problem with RangeValidator.
You'll need to use a CustomValidator instead, and manually verify the user's input is within the allowed range - including allowing scientific notation.

Resources