How to validate email address inputs? - asp.net

I have an ASP.NET web form where I can can enter an email address.
I need to validate that field with acceptable email addresses ONLY in the below pattern:
xxx#home.co.uk
xxx#home.com
xxx#homegroup.com

A regular expression to validate this would be:
^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$
C# sample:
string emailAddress = "jim#home.com";
string pattern = #"^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
if (Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase))
{
// email address is valid
}
VB sample:
Dim emailAddress As String = "jim#home.com"
Dim pattern As String = "^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
If Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase) Then
' email address is valid
End If

Here's how I would do the validation using System.Net.Mail.MailAddress:
bool valid = true;
try
{
MailAddress address = new MailAddress(email);
}
catch(FormatException)
{
valid = false;
}
if(!(email.EndsWith("#home.co.uk") ||
email.EndsWith("#home.com") ||
email.EndsWith("#homegroup.com")))
{
valid = false;
}
return valid;
MailAddress first validates that it is a valid email address. Then the rest validates that it ends with the destinations you require. To me, this is simpler for everyone to understand than some clumsy-looking regex. It may not be as performant as a regex would be, but it doesn't sound like you're validating a bunch of them in a loop ... just one at a time on a web page

Depending on what version of ASP.NET your are using you can use one of the Form Validation controls in your toolbox under 'Validation.' This is probably preferable to setting up your own logic after a postback. There are several types that you can drag to your form and associate with controls, and you can customize the error messages and positioning as well.
There are several types that can make it a required field or make sure its within a certain range, but you probably want the Regular Expression validator. You can use one of the expressions already shown or I think Visual Studio might supply a sample email address one.

You could use a regular expression.
See e.g. here:
http://tim.oreilly.com/pub/a/oreilly/windows/news/csharp_0101.html

Here is the official regex from RFC 2822, which will match any proper email address:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

I second the use of a regex, however Patrick's regex won't work (wrong alternation). Try:
[A-Z0-9._%+-]+#home(\.co\.uk|(group)?\.com)
And don't forget to escape backslashes in a string that you use in source code, depending on the language used.
"[A-Z0-9._%+-]+#home(\\.co\\.uk|(group)?\\.com)"

Try this:
Regex matcher = new Regex(#"([a-zA-Z0-9_\-\.]+)\#((home\.co\.uk)|(home\.com)|(homegroup\.com))");
if(matcher.IsMatch(theEmailAddressToCheck))
{
//Allow it
}
else
{
//Don't allow it
}
You'll need to add the Regex namespace to your class too:
using System.Text.RegularExpressions;

Use a <asp:RegularExpressionValidator ../> with the regular expression in the ValidateExpression property.

An extension method to do this would be:
public static bool ValidEmail(this string email)
{
var emailregex = new Regex(#"[A-Za-z0-9._%-]+(#home\.co\.uk$)|(#home\.com$)|(#homegroup\.com$)");
var match = emailregex.Match(email);
return match.Success;
}

Patricks' answer seems pretty well worked out but has a few flaws.
You do want to group parts of the regex but don't want to capture them. Therefore you'll need to use non-capturing parenthesis.
The alternation is partly wrong.
It does not test if this was part of the string or the entire string
It uses Regex.Match instead of Regex.IsMatch.
A better solution in C# would be:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[A-Z0-9._%+-]+#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}
Of course to be completely sure that all email addresses pass you can use a more thorough expression:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}

Related

query string parameter without value, only key

i have question about query string in asp.net:
standart query string with query string parameter is "www.mysity.url?key1=value1&key2=value2", but i need only check has query string key or not...yes, one of the correct decisions: www.mysite.url?reset=true, but this excess syntax for me.
in markup i use something like "<a href='UrlHelper.GetResetUrl()'>Reset</a>", this method return "www.mysity.url?reset", but in user side markup i have "Reset"
If you do not specify the name for a parameter it is taken as null.
Its value would be reset
So you would have to check it as follows:
if(Request.QueryString[null]=="reset")
{
//Take some reset action
}
a Quick and dirty solution is:
if(Request.Url.Query.Contains("?reset"))
{
// ok we have a reset
}
Assuming that you have a standard reset call ask as: www.mysity.url?reset and the reset url not have other parameters. If you have you can simple check for the reset keyword.
This code HttpContext.Current.Request["reset"] is always return null, so the next best thing if you like to make it hard, is to manual analyze your keys after the url.
All code that handles querystring parameters should be case insensitive. Browsers (or parts of internet infrastructure?) may convert the case.
One way to check if reset parameter is present in querystring:
bool reset = Request.Url.Query.IndexOf("reset", StringComparison.CurrentCultureIgnoreCase) > -1;

Character + is converted to %2B in HTTP Post

I'm adding functionality to a GM script we use here at work, but when trying to post (cross site may I add) to another page, my posting value of CMD is different than what it is on the page.
It's supposed to be Access+My+Account+Info but the value that is posted becomes Access%2BMy%2BAccount%2BInfo.
So I guess my question is: What's escaping my value and how do I make it not escape? And if there's no way to unescape it, does anyone have any ideas of a workaround?
Thanks!
%2B is the code for a +. You (or whatever framework you're using) should already be decoding the POST data server-side...
Just a quick remark: If you want to decode a path segment, you can use UriUtils (spring framework):
#Test
public void decodeUriPathSegment() {
String pathSegment = "some_text%2B"; // encoded path segment
String decodedText = UriUtils.decode(pathSegment, "UTF-8");
System.out.println(decodedText);
assertEquals("some_text+", decodedText);
}
Uri path segments are different from HTML escape chars (see list). Here is an example:
#Test
public void decodeHTMLEscape() {
String someString = "some_text+";
String stringJsoup = org.jsoup.parser.Parser.unescapeEntities(someString, false);
String stringApacheCommons = StringEscapeUtils.unescapeHtml4(someString);
String stringSpring = htmlUnescape(someString);
assertEquals("some_text+", stringJsoup);
assertEquals("some_text+", stringApacheCommons);
assertEquals("some_text+", stringSpring);
}
/data/v50.0/query?q=SELECT Id from Case
This worked for me. Give space instead of '+'

ASP.NET Routing - With and without a slash at the end

Considering the following Service Contract:
[WebGet(UriTemplate = "/stores")]
DTO.Stores GetAllStores();
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string name);
I can reach these two Urls: http://localhost/v1/stores and http://localhost/v1/stores/Joe. However the Url http://localhost/v1/stores/ (notice the slash at the end) returns me an "Endpoint not found" error. Ideally, I would like http://localhost/v1/stores/ to call GetAllStores().
How can I do that? Thanks!
I would try putting a tilde in. Perhaps "~/stores"?
Or, with routing, drop the "/" at the front.
What if you use "string? name" as parameter?
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string? name);
And since both methods you have are returning the same thing (DTO.Stores) you could use a single method to get the Stores instead of two (as you are doing now). Like this:
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string? name)
{
if(string.IsNullOrEmpty(name))
{
//get specific store
}
else
{
//get all stores
}
}
P.S.: I am not sure if that would work well with WCF, but give it a try. ;-)

Force ASP.NET textbox to display currency with $ sign

Is there a way to get an ASP.NET textbox to accept only currency values, and when the control is validated, insert a $ sign beforehand?
Examples:
10.23 becomes $10.23
$1.45 stays $1.45
10.a raises error due to not being a valid number
I have a RegularExpressionValidator that is verifying the number is valid, but I don't know how to force the $ sign into the text. I suspect JavaScript might work, but was wondering if there was another way to do this.
The ASP.NET MaskedEdit control from the AJAX Control Toolkit can accomplish what you're asking for.
I know an answer has already been accepted, but I wanted to throw out another solution for anyone with the same problem and looking for multiple workarounds.
The way I do this is to use jQuery format currency plugin to bind user input on the client side. Parsing this input on the server side only requires:
// directive
using System.Globalization;
// code
decimal input = -1;
if (decimal.TryParse(txtUserInput.Text, NumberStyles.Currency,
CultureInfo.InvariantCulture, out input))
{
parameter = input.ToString();
}
The only downfall to this is that the user can have javascript turned off, in which case the RegEx validator running server-side would work as a fall-back. If the control is databound, all you have to do is decimalValue.ToString("{0:c}") , as mentioned by others, in order to display the proper currency formatting.
The cool thing about this is that if the user enters the textbox and it shows $0.00 on the client side, the server-side if statement would return false. If your decimal value isn't nullable in the database, just change decimal input = -1 to decimal input = 0 and you'll have a default value of 0.
Another way to do this might be to place the dollar sign outside to the left of the text box. Is there a real need to have the dollar sign inside of the box or will a simple label do?
decimal sValue = decimal.Parse(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", sValue); }
else
{ string LableText = Convert.ToString(sValue); }
string sValue = Convert.ToString(txtboxValue.Text.Trim());
// Put Code to check whether the $ sign already exist or not.
//Try making a function returning boolean
//if Dollar sign not available do this
{ string LableText = string.Format("{0:c}", "sValue"); }
else
{ string LableText = Convert.ToString(sValue); }
In the .CS you could do a pattern match along the lines of,
string value = text_box_to_validate.Text;
string myPattern = #"^\$(\d{1,3},?(\d{3},?)*\d{3}(\.\d{0,2})|\d{1,3}(\.\d{2})|\.\d{2})$";
Regex r = new Regex(myPattern);
Match m = r.Match(value);
if (m.Success)
{
//do something -- everything passed
}
else
{
//did not match
//could check if number is good, but is just missing $ in front
}

How to create an ASP.NET custom control with a dash in the name?

I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:
<rp:do-something runat="server" id="doSomething1" />
I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the tagMapping element doesn't quite match up for what I'd like to do.
I wouldn't think this is possible due to the restrictions on class namings. I don't believe you can refer to a control class in markup without refering to it by name
Is there a specific reason you need the hyphen?
John, you're right. I did some searching in Reflector and it looks like it doesn't get there:
Type ITagNameToTypeMapper.GetControlType(string tagName, IDictionary attribs)
{
string str;
string str2 = this._nsRegisterEntry.Namespace;
if (string.IsNullOrEmpty(str2))
{
str = tagName;
}
else
{
str = str2 + "." + tagName;
}
if (this._assembly != null)
{
Type type = null;
try
{
type = this._assembly.GetType(str, true, true);
}
Implemented in System.Web.UI.NamespaceTagNameToTypeMapper, System.Web.
#Jonathan: I have a specific business reason for wanting to do it this way. Oh well.

Resources