Validation Control Chaining - asp.net

Another "I am pretty sure I know the answer, but I'll ask anyway just in case" question.
(The answer I think being "no, there isn't")
Is there any built-in way to chain validators in ASP.NET (.Net 4.0) without the need to write <asp:CustomValidator> code? So that one validator will only be checked if another validator has passed it's validation?
For instance, say you have two <asp:DropDownList> controls, both with the exact same options, including a "blank" entry at the start (because you don't want anything pre-selected, that is a decision the user must consciously make)...
<asp:DropDownList runat="server" id="dd1">
<asp:ListItem Value="-1" Text=""/>
<asp:ListItem Value="1">One</ListItem>
<asp:ListItem Value="2">Two</ListItem>
...
</asp:DropDownList>
<asp:DropDownList runat="server" id="dd2">
... with identical list of items as dd1
I would put two <asp:CompareValidator> controls, one associated with each of the above <asp:DropDownList> controls
<asp:CompareValidator runat="server" id="val1" ControlToValidate="dd1"
ValueToCompare="-1" Operation="Not Equal" ErrorMessage="Select DD1" />
<asp:CompareValidator runat="server" id="val2" ControlToValidate="dd2"
ValueToCompare="-1" Operation="Not Equal" ErrorMessage="Select DD2" />
These work fine, and shows the appropriate error if the original "blank" entry is the selected item.
However, I need the two items to be different, so I add another <asp:CompareValidator>...
<asp:CompareValidator runat="server" id="val3" ControlToValidate="dd1"
ControlToCompare="dd2" Operation="Not Equal" ErrorMessage="DD2 must be different to DD1" />
The result of this is that if both DD1 and DD2 have the "blank" as their selected items, all three validators will fire on a form submit. This is incorrect, as val3 should only be validated if val2 has successfully validated.
The obvious solution is to use a <asp:CustomValidator> instead, and handing the situation myself... but I thought I'd ask if there was a built-in way of making val3 only validate if val2 was valid.

Related

ASP.NET "stacked" regular expression field validators

I have 2 ASP.NET regular expression validators:
^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$ check whether the email address is valid
#(adres.pl|vp.pl) check if value contains any of these strings
The problem now is:
The strings in bullet 2 above should NOT be allowed, so o email address "john#adres.pl" should not be allowed.
However, the validators are only positive, meaning that they check if they DO contain the structure.
So when someone currently enters "test#test.com", I get "invalid value"
My code below:
<asp:TextBox ID="tbEmail" runat="server" />
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="emailinvalid" ValidationExpression="^\s*[-+.'\w]+#\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="rev1" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(adres.pl|vp.pl)" ID="rev2" runat="server"/>
I was initially thinking of combining expressions 1 and 2, but then I wouldn't know which one fails, and don't know which error to display.
What I would expect is:
"35435gd" -> emailinvalid
"john#adres.pl" -> not allowed
"john#gmail.com" -> all validators are ok
Or perhaps validator rev2 should only execute if rev1 does not throw an error, so "stacking" for a lack of a better term, which a: seems cumbersome and b: I wouldn't know how to do it.
How can I solve for this?
UPDATE 1
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
"gddg" results in "not allowed", whereas I'd expect "invalid".
When I switch the order of these validators, both errors "invalid" and "not allowed" show.
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="invalid" ValidationExpression="^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$" ID="RegularExpressionValidator5" runat="server"/>
<asp:RegularExpressionValidator ControlToValidate="tbEmail" ErrorMessage="not allowed" ValidationExpression="#(?!(?:adres|vp)\.pl\b)" ID="RegularExpressionValidator4" runat="server"/>
You can use a single pattern and you might write your existing pattern as:
^\s*[-+.'\w]+#(?!(?:adres|vp)\.pl\b)\w+(?:[-.]\w+)*\.(?!co\s*$)\w{2,}\s*$
The part excluding either adres.pl or vp.pl can be written as #(?!(?:adres|vp)\.pl\b) excluding those matches directly after the #.
You could also use #(?!(?:adres|vp)\.pl\s*$) if that is the last part of the email address just like you currently do for this part \.(?!co\s*$)
See a regex demo.
Note that your pattern would allow leading and trailing whitespace chars for the e-mail address.

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.

Using ID as a rangevalidator value ASP

I've been working on a small game and I'm stuck trying to figure out how I can convert an ID that a user enters to become an integer value. I'm wanting to create a rangeValidator that specifies that a bet entered by a user can only go from 0 to the total amount of money they currently have.
current money: <asp:label ID="currentMoney" runat="server" Text=""></asp:label> <br />
Place bet: <asp:textbox ID="bet" runat="server"></asp:textbox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" ForeColor="Red" ControlToValidate="bet" runat="server" ErrorMessage="bet must be less than or equal to current money"> </asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="bet" type="Integer" MinimumValue="1" MaximumValue="currentMoney" ></asp:RangeValidator>
I'm not sure if there is a way to convert the currentMoney ID which gets originally entered by a user at an earlier part of my code to be used as the maximum value for my range validator. Is there any suggestions anyone might have?
You'd have to set the MaximumValue property in code:
RangeValidator2.MaximumValue = currentMoney.Text
As long as everything happens on the server. If not, then you'd have to update the client API; if you do that, when a postback happens, you'd have to update on the server or update on the client again (as these are not sent back to the server). I'm not quite sure how to do that, but googling should provide a solution.

what is the use of Eval() in asp.net

What is the use of Eval() in ASP.NET?
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.
It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

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