ASP.Net - validating email address with regexp? - asp.net

When validating an email address with the regex validation component, an additional RequiredFieldValidator must be added to ensure there is a value present.
I've mostly taken care of this with a CustomFieldValidator, and taking care of this with Javascript.
Is there a better way of doing this?

Why wouldn't you just use the RegularExpressionValidator and the RequiredFieldValidator?
If you use a CustomFieldValidator you will need to implement a javascript check and a server side check as well. Using the other two validation controls together need no extra implementation except for a couple of attributes being set and it is the expected way of doing this type of validation with WebForms.
Consider the next programmer that is going to come along and see your different setup and wonder why you went to all this extra work when none of it was needed.

If you fancy doing it in the background code you could use the following function:
Function checkEMail(ByVal email As String) As Boolean
Dim pattern As String = "^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*""\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*"")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$"
Dim emailCheck As Match = Regex.Match(email, pattern)
If emailCheck.Success Then
checkEMail = True
Else
checkEMail = False
End If
Return checkEMail
End Function

Related

QueryString not accepting & - Needs to

I need to be able to handle an HTML encoded ampersand in my .Net code.
So the Url is
http://myite.com/index.aspx?language=en&Refresh=true
There is no way of changing this as it has been generated by something else so this is out of my control.
How can I read the Refresh parameter?
I have tried
HttpUtility.UrlDecode(Request.QueryString("Refresh"))
but my Request.QueryString("Refresh") is actually empty, so this is pointless, as is Uri.EscapeDataString.
This can't be the first time this has happened, but I'm struggling to find a solution, as most people would say use UrlEncoding, but as I said, the Url is out of my control.
& in your query string should be %26.
Since you can't correct the url.
You can read the refresh value as:
Request.QueryString("amp;Refresh");
Note that the developer of the service you are using may correct this in future.
It would be good to be ready for that already.
var refresh = Request.QueryString("amp;Refresh");
if(String.IsNullOrEmpty(refresh))
refresh = Request.QueryString("Refresh");
nunespascal answer pretty much solves your problem. There are some alternate methods.
If its guaranteed that your Refresh parameter is the second key in the QueryStringCollection then you can use Request.QueryString(1)
Another method is to do a Contains on the QueryStringCollection.
If Request.QueryString IsNot Nothing AndAlso Request.QueryString.AllKeys.Count() > 0 Then
Dim refreshKey = Request.QueryString.AllKeys.FirstOrDefault(Function(nv) nv.Contains("Refresh"))
If refreshKey IsNot Nothing Then
Dim refreshValue = Request.QueryString(refreshKey)
End If
End If

A Minor, but annoying niggle - Why does ASP.Net set SQL Server Guids to lowercase?

I'm doing some client-side stuff with Javascript/JQuery with .Net controls which expose their GUID/UniqueIdentifier IDs on the front end to allow them to be manipulated. During debugging something is driving me crazy: The GUIDs in the db are stored in uppercase, however by the time they make it to the front end they're in lowercase.
This means I can't quickly copy and paste IDs into the browser's console to execute JS on the fly when devving/debugging. I have found a just-about-workable way of doing this but I was wondering if anyone knew why this behaviour is the case and whether there is any way of forcing GUIDs to stay uppercase.
According to MSDN docs the Guid.ToString() method will produce lowercase string.
As to why it does that - apparently RFC 4122 states it should be this way.
The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input.
Also check this question on SO - net-guid-uppercase-string-format.
So the best thing you can do is to call ToUpper() on your GUID strings, and add extension method as showed in the other answer.
If you're using an Eval template, then I'd see if you can do this via an Extension method.
something like
public static string ToUpperString(this Guid guid, string format = "")
{
string output = guid.ToString(format);
return output.ToUpper();
}
And then in your Eval block,
myGuid.ToUpperString("B")
Or however you need it to look.
I'm on my Mac at the moment so I can't test that, but it should work if you've got the right .Net version.

Check if an Object exists in VBScript

I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.
I have an array of imagefile paths, like so:
dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"
This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).
If Not banners Is Nothing then
' then loop through the Dictionary and make a list of image links
End if
The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error
What's the proper way to check if an object exists in VB Script?
#Atømix: Replace
If Not banners Is Nothing then
and use
If IsObject(banners) Then
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
#Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)
IsObject could work, but IsEmpty might be a better option - it is specifically intended to check if a variable exists or has been initialised.
To summarize:
IsEmpty(var) will test if a variable exists (without Object Explicit), or is initialised
IsNull(var) will test if a variable has been assigned to Null
var Is Nothing will test if a variable has been Set to Nothing, but will throw an error if you try it on something that isn't an object
IsObject(var) will test if a variable is an object (and will apparently still return False if var is Empty).
If a variable is declared, but not initialized, its value will be Empty, which you can check for with the IsEmpty() function:
Dim banners
If IsEmpty(banners) Then
Response.Write "Yes"
Else
Response.Write "No"
End If
' Should result in "Yes" being written
banners will only be equal to Nothing if you explicitly assign it that value with Set banners = Nothing.
You will have problems, though, with this technique if you have Option Explicit turned on (which is the recommendation, but isn't always the case). In that case, if banners hasn't been Dimed and you try to test IsEmpty(banners), you will get a runtime error. If you don't have Option Explicit on, you shouldn't have any problems.
edit: I just saw this related question and answer which might help, too.
Somewhat related is IsMissing() to test if an optional parameter was passed, in this case an object, like this:
Sub FooBar(Optional oDoc As Object)
'if parameter is missing then simulate it
If IsMissing(oDoc) Then Dim oDoc as Object: oDoc = something
...
You need to have at least dim banners on every page.
Don't you have a head.asp or something included on every page?
Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered.
The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here:
Is there any way to check to see if a VBScript function is defined?

Can I read Captcha data from JavaScript in a secure way?

We use Captcha control in a registration form that we make full client validation for all fields in JavaScript ( JQuery ) beside server validation ..
I tried a lot of ways but all will write the Captcha value in JavaScript that can be accessed by anyone :(
I search if is there any way that allow me validate Captcha value in client side using JQuery in secure way or it can't be done ?
It cannot be done.
Javascript is client-side, as you know, and any code client-side has to be treated as potentially compromised as you don't have control over it.
At best, you could resort to sending up a salted hash of the value along with the salt, but even that in itself could be used to test guess values before actually submitting it.
Everything else relies on calls to the server.
As per comment request, here's the general idea:
Firstly, on the server, calculate a random string to be used as the salt. This should be roughly unique every request. The purpose of this string is to prevent rainbow table attacks.
Now, saving this string separately, but also create another string that is the concatenation of random string and the Captcha answer. Of this new combined string you generate the hash (for example, SHA-1) of it.
using System.Web.Security;
...
string hashVal = FormsAuthentication.HashPasswordForStoringInConfigFile(combined, "SHA1");
Both the random string and the hash value need to be placed in the page for the javascript to be able to read.
On the client side, when a user answers the Captcha, take the random string and concatenate it with the answer (getting the idea here?). Taking this string, you can use something like the SHA-1 JQuery plugin to hash it and compare it with the pre-computed hash you sent up.
hashVal = $.sha1(combinedString)
If it matches, it is (almost) certainly the correct answer. If it doesn't, then it is 100% the wrong answer.
you could use ajax to post the current value to the server, which would respond true or false. that would keep you from doing a real post and also from giving away the catpcha's value in html.
My solution )) Every time when page shows captcha to the user, you can dynamically generate obfuscated JavaScript functions(i think the best way 5 or 10).
For example, one function(or 3)) ) can set cookies with pregenerated hash(server returns it)(from real value of the captcha), other functions must realize server side algorithm to check value which user's typed. I can say that it works for 100%, because it is very hard to parse dynamically javascript + we set user cookies on client side(It is very hard for Bots's to find out where and how you set and check cookies), by using JavaScript.

ASP.Net word count with a custom validator

A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:
Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
'' 10 words
args.IsValid = args.Value.Split(" ").Length <= 10
End Sub
Does anyone have a more thorough/accurate method of getting a word count?
You can use one of the builtin validators with a regex that counts the words.
I'm a little rusty with regex so go easy on me:
(\b.*\b){0,10}
This regex seems to be working great:
"^(\b\S+\b\s*){0,10}$"
Update: the above had a few flaws so I ended up using this RegEx:
[\s\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\xBF]+
I split() the string on that regex and use the length of the resulting array to get the correct word count.
I voted for mharen's answer, and commented on it as well, but since the comments are hidden by default let me explain it again:
The reason you would want to use the regex validator rather than the custom validator is that the regex validator will also automatically validate the regex client-side using javascript, if it's available. If they pass validation it's no big deal, but every time someone fails the client-side validation you save your server from doing a postback.

Resources