views:

31

answers:

3

Hey,

I have a TextBox, and I want to force the user to type an email format in this field like ([email protected]) ?

I don't want to use FilteredTextBoxExtender or the RegularExpressionValidator.

I want to do it manualy.

A: 

You are really going to reinvent the wheel. But if it is your wish, you have to use string manipulation functions built in to the String object.

First do a check whether there is a in @ symbol in the text.

Use String.Contains to check that.

Or you can use String.IndexOf to check whether the @ symbol is present, and if present which index is it present. (considering the string as an array of characters)

And then check whether there are any (and how many) characters present before the @ symbol. If the symbol @ symbol was in the 4th index, then you know there are 3 characters before etc.

There's plethora of functions for the String object. You may have to use Length function and String.SubString to retrieve parts of the string.

Get the indexes of the @ symbol and the . symbol and check whether there are at least 3 characters in between.

I really cant seem to think of all the possibilities but first list down all the possibilities and check them one by one.

You can also use the Contains method to check whether illegal characters are present :)

EDIT: String.LastIndexOf will return the last index where a specified character was found ;)

And you count and check whether the @ symbol was found more than once etc

String.IndexOfAny(Char[])

String.IndexOfAny Method (Char[], Int32)

String.IndexOfAny Method (Char[], Int32, Int32)

Ranhiru Cooray
First, if you're going to be looking for a basic pattern, just use a regular expression. All this business with checking index positions sounds like a good recipe for generating a very long function. But also, rules like "check whether there are at least 3 characters in between [the `@` and first `.`] are already invalid. `[email protected]` might very well be the address of an actual employee of American Airlines, for example.
VoteyDisciple
I use RegularExpressions for validation :) It's just that he particularly needs to do it manually. And the 3 characters in between was just an example. He should use these methods + his own rules and test whether the string satisfy all his rules ;) He wanted to do it manually :)
Ranhiru Cooray
+1  A: 

Use the MailAddress class of System.Net.Mail. If what you pass into it is not a valid email address it will fail.

Example:

http://stackoverflow.com/questions/1331084/how-do-i-validate-email-address-formatting-with-the-net-framework

klabranche
A: 

This is the best way I found on internet.

Regex.IsMatch(YourStringEmail, "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + _
                  "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")

Thank you.

dotNET