Should Regular Expressions be used over other validation methods? - asp.net

Given a Textbox, that should contain a numeric value:
<asp:TextBox ID="txtHoldsAnInt" runat="server" />
In our codebase, generally a RegularExpressionValidator is used for all validation (except required fields) such as the following:
<asp:RegularExpressionValidator ErrorMessage="..." ControlToValidate="txtHoldsAnInt"
Text="*" runat="server" ValidationExpression="^[0-9]{1,8}$" />
Alternately, a RangeValidator could be used to get the same result:
<asp:RangeValidator ErrorMessage="..." ControlToValidate="txtHoldsAnInt"
MinimumValue="0" MaximumValue="99999999" Type="Integer" runat="server" />
Does the RegularExpressionValidator have an advantage over other validators, even when another validator would work? Are there any advantages to always using a RegularExpressionValidator?

If you are familiar with regular expressions, then I would recommend using the <asp:RegularExpressionValidator. You are correct that there is no noticeable difference when they are equal to each other, but the RegularExpressionValidator allows for easy editing later on when specifications change. For example with a RegularExpressionValidator it would be easy to allow for a percent sign at the end or any other change that might be requested.

In terms of functionality/end result, there is no difference between using the two. I would suggest using the range validator other validators if the situation permits and it satisfy your needs. It is much easier for someone to understand <asp:RangeValidator than to understand ^[0-9]{1,8}$. While the RegularExpressionValidator will give you a much higher degree of control, if that control is not needed, then go for the simple solution and ease your maintenance efforts.

Related

Simple VB.NET RegularExpressionValidator not working

I'm embarrassed to ask but I've been at this for hours trying multiple solutions with no luck.
I'm trying to validate the file name used by my asp.net FileUploadControl.
All I want to do is test if the file starts with "RFTrack".
<asp:FileUpload id="FileUploadControl" MaxLength="75" runat="server" CssClass="input" />
<asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server"
ErrorMessage="Must start with 'RFTrack'" ValidationExpression ="^rftrack"
ControlToValidate="FileUploadControl" >
</asp:RegularExpressionValidator>
Using this validation, I can not get any test files starting with "RFTrack" to pass the validation. I have even tried using a file just named "rftrack" to no avail.
I used multiple online Regex testers that have confirmed that my regex is correct. I have also tried things like
^(rftrack|RFTRACK)
With no luck. I'm sure I'm just missing something obvious.

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.).

Using compare validator

Is there a way in using compare validator that when you use lessthanequal or greaterthanequal operator it automatically treat the type as int? Let's say adding additional tag in web config or any setup? thanks
CompareValidator has a Type property that you could use.
<asp:CompareValidator ID="CV_GreaterTen"
Type="Integer"
Operator="GreaterThanEqual"
ValueToCompare="10" runat="server" ErrorMessage="Must be at least 10" ControlToValidate="Textbox1">*
</asp:CompareValidator>
Apart from that, there is no automatism.
By the way, such magical(mostly hidden) settings would be a good source for future problems.

ASP.NET compare end time and start time with customvalidator

I have two text boxs for time input. I'm trying to compare two time with format : 10:14:23 AM. Then End-TIme must be greater or equal to Start-Time. The ASP.NET CompareValidator doesnt offer the time type, so I'm thinking of using the Customvalidator. I never use Customvalidator to compare the two text boxs for time input before. How to compare the two time? Thank you.
Have you looked at the MSDN entry for the CustomValidator? It specifies usage and gives an example of how to use it:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx
<asp:CompareValidator
ID="ClosedTime_CompareValidator"
runat="server"
ControlToCompare="OpenedTimeTextBox"
ControlToValidate="ClosedTimeTextBox"
ValidationGroup="Submit"
Operator="GreaterThanEqual"
Display="Dynamic">
<img
src="./FormImages/warning.gif"
alt="The entry is not recognizabledate."/>

In asp.net, I need to add validator to textbox that forces the input to be numbers

In asp.net, I need to add a validator to a textbox that forces the input to be numbers.
Is this built in?
I have already added a required field validator to the textbox.
You could use a Regex Validator to ensure the text is numeric
I think the regex would be
[0-9]*
e.g.
<asp:TextBox ID="tbxNumbers" runat="server" />
<asp:RegularExpressionValidator ID="revNumericValidator" runat="server"
ValidationExpression="^[0-9]*$" ControlToValidate="tbxNumbers" ErrorMessage="Must be Numeric" />
EDIT:
As the other two posters also pointed out you can also use \d to represent a Numeric Character
<asp:RegularExpressionValidator runat="server"
ControlToValidate="numbersOnlyTextBox"
ErrorMessage="Enter only numeric characters."
ValidationExpression="^\\d+$" />
Use a range validator.
<asp:TextBox ID="MyTextBox" MaxLength="4" Width="75"
Text="0" runat="server"></asp:TextBox>
<asp:RangeValidator ID="MyRangeValidator" Display="Static" Type="Integer"
MaximumValue="9999" MinimumValue="0" EnableClientScript="true"
ControlToValidate="MyTextBox" runat="server" SetFocusOnError="true"
ErrorMessage="Ooops"></asp:RangeValidator>
This permits you to use numbers with decimal places (by using Type="Double" or "Currency"), or other kinds of numbers that Windows recognizes.
Check MSDN for more info on the Range Validator Control.
I think there needs to be more clarification of the requirements here. What kind of numbers are we talking about? Positive integers? Any integer? A number with a decimal place? What about commas in the number (1,000)?
I recommend a RegularExpressionValidator to do your work, but these questions make a difference when it comes to which RegEx you use.
In order to provide a better user experience, another thing to add is an AjaxToolkit FilteredTextBox extender, with a FilterType of either "Custom, Numbers" or just "Numbers". The first choice is for when you want to be able to specify decimal points and negative numbers. In that case you must also specify the ValidChars attribute with something like "-.". This will stop a user from entering characters that are not going to make up a valid number such as -123.45 . Note that it does not stop the user from entering the '-' & '.' in incorrect places e.g. "2-..-3" can still be entered. You will need the validators mentioned in other answers to catch these cases.
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Custom, Numbers"
ValidChars="-." />
Or
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server"
TargetControlID="numbersOnlyTextBox"
FilterType="Numbers" />

Resources