How can I encrypt my ValidationExpression in VB.net? - asp.net

I'm very new to asp and vb.net, I've just learned about regular expression validation but one thing is bugging me: How can I hide my expression from being viewed on my source code?
The plan is to make a very simple 'login' type of page. I know this goes against all that is holy in this kind of operations, but it's just something I'd like to try out.
Also, after the expression has been validated, I want to load another page, I was thinking of achieving this with:
<asp:TextBox ID="txtcp" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="CP Errada"
Display="Dynamic" ControlToValidate="txtcp" ValidationExpression="admin"></asp:RegularExpressionValidator>
and in vb:
If txtcp is validated then
Response.Redirect("mypage.aspx")
end if
But the syntax on this IF is obviously not right, any help would be great.

You can shrink the size of your Regex Validator by using the following.
<asp:TextBox ID="txtcp" runat="server" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" />
And then in your Code behind
Function Page_Load()
With RegularExpressionValidator1
.ErrorMessage="CP Errada"
.Display="Dynamic"
.ControlToValidate="txtcp"
.ValidationExpression="admin"
End With
End Function
Function SubmitButton_Clicked()
If Page.IsValid Then
Response.Redirect("mypage.aspx")
End If
End Function
Unfortunately you can't encrypt it since the whole point of validation is to use Client Side Javascript. It is bad (in fact VERY BAD) to use a regular expression to validate a username in the way that I 'think' you're doing it in your example. The right thing to do for you, honestly, is to just use the build in ASP.NET Membership Provider. It is seriously easy to learn, it's mostly secure by default, and best of all... it's "no Fuss, no Muss".

Related

Escape HTML-entities and avoid HTML-injection in WebForm Label?

So, I thought I was a "veteran" ASP.NET WebForms developer; however, I came across this recently and was (unpleasantly) surprised that the output is not escaped:
<asp:Label Text='<%# Eval("UserData") %>' runat="server" />
Imaging where the Eval returns "<h1>joke is on you" or something more malicious to the correct rendering/security of the page.
The reason there is a Label instead of the <%# %> directly was so that, as incorrectly presumed, the contents of "UserData" would be correctly escaped for HTML. However, this apparently is not the case and the above scenario results in <h1> elements being created in the HTML markup.
Then the question can be distilled as:
Given arbitrary user input, that is to be presented as "plain text", what is an easy/reliable/secure method to insert data into the page (in a span) with correct escaping?
As per above, it should run in the context of a data-bound control. I am aware of HttpUtility.HtmlEncode, but I would like to entertain the idea of still using a control - perhaps there is a standard control for this task that I missed - to represent this case safely, without the need for wrapping the Eval. If this is misguided, based on logic or experience, it would be good to include in replies. I would not reject the notion that my use of Label in this case is entirely inappropriate.
Unfortunately, due to needing to run in a SharePoint 2010 context, I target ASP.NET for .NET 3.5, and not ASP.NET 4.
What about:
<asp:Label Text='<%#: Eval("UserData") %>' runat="server" />
This escapes the output of the eval, this only works in .NET 4.
For .NET 3.5 a solution can be:
CodeBehind:
public object EvalEncode(object container, string expression)
{
string ouput = DataBinder.Eval(container, expression).ToString();
return HttpUtility.HtmlEncode(ouput);
}
MarkUp:
<%# EvalEncode(Container.DataItem, "Text") %>
Instead of using HttpUtility.HtmlEncode, it's maybe better to use the AntiXSS library. For .NET 4 users it's already backed into the framework.
You could use an <asp:Literal ...></asp:Literal> control instead of the Label. The literal has a Mode property which you can use to tell the control to html encode its output.
Instead of this:
<asp:Label Text='<%# Eval("UserData") %>' runat="server" />
Try using:
<asp:Literal Text='<%# Eval("UserData") %>' Mode="Encode" runat="server"></asp:Literal>
Use the Microsoft Web Protection Library(Anti-XSS library) provided by microsoft for such purposes.
Security is hard, don't try to do it yourself. There is always be some hacker who is smarter.
You use it as follows:
<asp:Label Text='<%= Microsoft.Security.Application.AntiXss.HtmlEncode(Eval("UserData")) %>' runat="server" />

How to show regular expression validation's message after button click only?

Below is my html code. I have a email textbox and there is a login button. I have added a required field validator and regular expression validator for email textbox.
The problem is that when I type some thing in the email textbox browser's auto suggestion shows some list of emails. When I select any of those emails by using down arrow key and enter key it shows the error message for regular expression validation even though email is in proper format.
<asp:RequiredFieldValidator ID="reqValUserName" runat="server"
ErrorMessage="Email is required!"
ControlToValidate="txtUserName"
ValidationGroup="validateCredential"
Display="Dynamic">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Static">
</asp:RegularExpressionValidator>
<asp:TextBox ID="txtUserName" runat="server"
TabIndex="1" CssClass="inputCredential" MaxLength="60"
AccessKey="E"
ValidationGroup="validateCredential">
</asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CssClass="btnPrimary"
Text="Login" onclick="btnLogin_Click"
ValidationGroup="validateCredential"/>
In this image as you see if I select the email from the suggestion and press enter it is showing the wrong email validation message.
Can anyone please let me know, how to stop this kind of message display?
If there is any clarification needed regarding the question then please add it as a comment.
You could add the EnableClientValidation="false" attribute to the regex validator so that it only checks the format on the server after the other validators have been passed.
Or follow the advice here:
What determines the order validators fire in?
Also add regular expression validator
for email text box
<asp:RegularExpressionValidator ID="regtxtPrimaryEmail" runat="server" ControlToValidate="txtEmailId"
Display="Dynamic" CssClass="cssVal" ToolTip="Invalid email." ValidationGroup="registration"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
Then it will not submit until the email format correct.
It seems your some controls has autopostback="true" and your these controls are in update panel if not then what you can do is..Remove the display properties of all the validation controls and on btnLogin_Click Event call Validate(); Method.
Also read more In Depth detail on Validators on MSDN
you'll certainly get your answer....
Thanks for all your answers and suggestions.
Below is what I have done after going through all the answers.
<asp:RegularExpressionValidator ID="regValUserName" runat="server"
ErrorMessage="Incorrect format!"
ControlToValidate="txtUserName"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
ValidationGroup="validateCredential"
Display="Dynamic" EnableClientScript="false">
</asp:RegularExpressionValidator>
As you can see, I have added EnableClientScript="false" so that the error message will not be shown when I type half of email and select from auto suggestion and press enter.
Now the problem was it was always checking for whether entered credentials are correct of not as it was doing validation in server side. So I had some unnecessary code execution and database interaction.
So in click event handler of login button I did following change.
if(Page.IsValid)
{
// My credential check code
}
So the above block of code will run code for checking correctness of entered credentials only if they are in proper format.
But I am still looking for a better answer. This is only a work around. Because when it comes to performance server side validation can never match client side validation. Here I am compromising with usability. As I want user to be notified immediately after he/she enters a wrong formatted email. This can be achieved by using javascript, but I wonder if there is any way we can achieve it using validator controls..
This is happening because the client-side REV is validating on the partial input. For example, in the above illustration, the REV is validating "r" as its input. In order to verify this,
type in the entire email address "rupeshn#aol.com" >> then
select the suggested email using the down arrow >> then
hit the enter key.
The REV will not complain this time.
As for the solution: implement the REV in javascript. Add a label next to the textbox for error message. Call the js when the cursor exits the textbox. If the validation fails, find the label in the js and add the error message.
Just see the properties of the validator there you will find 'Display' property under Appearance section, set it to dynamic and VOLA!!

debug a CompareValidator (ASP.NET)

What is the best way to debug a CompareValidator that always fails the validation? Is there any way to see what the values are that it's comparing to maybe get a clue as to what's going wrong?
Use Firebug to debug the javascript that .Net inserts
If you are not familiar with the other debugging methods, easiest way for you may be utilizing the Response.Write calls to print the values in your button event to see if they are equal to each other:
Response.Write(TextBox1.Text.ToString().Trim());
Response.Write(TextBox2.Text.ToString().Trim());
Response.End();
Update
For simplicity, I will use CompareValidator to check a data type.
You probably have something similar to the following in your ASPX (client side) code:
<asp:TextBox ID="txtTest" runat="server" />
<asp:CompareValidator ID="cvTest" runat="server"
ControlToValidate="txtTest"
Operator="DataTypeCheck" Type="Date"
Display="Dynamic" ErrorMessage="Incorrect format!" />
<asp:Button ID="btnTest" Text="Test Compare Validator"
onclick="btnTest_Click" runat="server" />
In your codebehind (server side), put the following in your btnTest_Click event to see the value that is entered in txtTest:
Response.Write(txtTest.Text.ToString().Trim());
Response.End();
But keep in mind that there more robust debugging utilities that VS offers. This is just a quick-and-dirty way for your purpose.

Regular expression multiline validator

In my ASP.NET Web Form I have a multiline TextBox which should be validated with RegularExpression Validator. Text box should contain one or more strings "a" (just 'a' char, nothing else).
So far I got these regular expressions for my RegularExpressionValidator object:
(?m:(^a$)+)
(?m:\A(^a$)+\Z)
(?m:^a$)
and some others. Neither works. Guess there is something fundamental I'm not getting yet.
Could you please tell me where I'm wrong?
Here's the code involved.
A Button (just for postbacks):
<asp:Button ID="Button1" runat="server" Text="Button" />
The TextBox:
<asp:TextBox ID="TextBox1" runat="server" Rows="10" TextMode="MultiLine"></asp:TextBox>
And the regex validator:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RegularExpressionValidator"
ValidationExpression="(?m:(^a$)+)"></asp:RegularExpressionValidator>
There is nothing else on that Web Form. I've only added those controls and modified properties. I've even did all this using VS GUI.
Using CustomValidator and doing Regex.Match(TextBox1, #"(?m:(^a$)+)") in it works just fine. Something is wrong with RegularExpressionValidator I guess.
If you want to match multiple lines, don't forget to also match the line terminators; they are not implied in $.
(?m:(^a$\r?\n?)+)
might work better.
This matches
a
or
a
a
a
etc.
And, since you're asking for a tutorial, how about regular-expressions.info?

ASP.NET TextBox filter

is there a simple way to suppress certain keystrokes within a textbox? for example if i only want to allow numbers.
There's nothing built-in, you will need to write some JavaScript to capture and ignore the keys you want to disallow.
Or you can use this FilteredTextBox control extender, from the ASP .NET AJAX Control Toolkit
You could also use a <asp:CompareValidator>. E.g.
<asp:CompareValidator ID="valNumbersOnly" runat="server"
ControlToValidate="controlYouWantToValidate"
Operator="DataTypeCheck"
Type="Integer"
ErrorMessage="Please enter only numbers">*</asp:CompareValidator>
Or you could go even further and use a regular expression validator.
These solutions will work with and without javascript, so they will validate client side and server side. Not everyone has javascript turn on!
HTHs,
Charles

Resources