Validation of textbox input in C# - c#

How to validate a mobile number textbox and email textbox using regular expressions in C#?
I want to validate these first at the front end itself so that the database doesn't receive any invalid input or rather even checks for it.
I am using Windows Forms.

You can use System.Text.RegularExpression
I'll give you an example for e-mail validation
then declare a regular expression like
Regex myRegularExpression = new
Regex(" \b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b");
and say your e-mail textbox is txtEmail
then write,
if(myRegularExpression.isMatch(txtEmail.Text))
{
//valid e-mail
}
Update
Not an expert on regular expressions,
Here's the link to Regular expression to validate e-mail
you can find more details about the regEx from the link provided.

//for email validation
System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(#"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
if (txt_email.Text.Length > 0)
{
if (!rEMail.IsMatch(txt_email.Text))
{
MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt_email.SelectAll();
e.Cancel = true;
}
}
//for mobile validation
Regex re = new Regex("^9[0-9]{9}");
if (re.IsMatch(txt_mobile.Text.Trim()) == false || txt_mobile.Text.Length > 10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txt_mobile.Focus();
}

This code will check whether an email address is valid:
string inputText = textBox1.Text;
if (Regex.IsMatch(inputText,
#"^(?("")("".+?""#)|(([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}))$"))
{
MessageBox.Show("yes");
}
else
{
MessageBox.Show("no");
}
(source: http://msdn.microsoft.com/en-us/library/01escwtf.aspx)
For phone numbers, it's not so simple - the answer depends on where in the world you are, whether you want to allow international numbers, how mobiles are numbered (for example, in the USA, you can't tell from a phone number alone whether it's a mobile number or not). Look up "Telephone numbering plan" on Wikipedia for more information.

In ASP.NET you can use a RegularExpressionValidator control.
To determine the regular expression itself, you can experiment with a tool like Expresso.
Be aware that validating emails with regular expressions is a hard task, if you want to allow all the possibly valid email formats; probably the best thing to do in that case would be to send an email to the entered address with a confirmation link, and when that link is clicked, you assume that the mail is valid.

See Email Address Validation Using Regular Expression (The Code Project) for email validation and see Best practice for parsing and validating mobile number (Stack Overflow) for mobile number validation.

I do the numeric validation this way as shown in the code below.
No need for checking char by char and user culture is respected!
namespace Your_App_Namespace
{
public static class Globals
{
public static double safeval = 0; // variable to save former value!
public static bool isPositiveNumeric(string strval, System.Globalization.NumberStyles NumberStyle)
// checking if string strval contains positive number in USER CULTURE NUMBER FORMAT!
{
double result;
boolean test;
if (strval.Contains("-")) test = false;
else test = Double.TryParse(strval, NumberStyle, System.Globalization.CultureInfo.CurrentCulture, out result);
// if (test == false) MessageBox.Show("Not positive number!");
return test;
}
public static string numstr2string(string strval, string nofdec)
// conversion from numeric string into string in USER CULTURE NUMBER FORMAT!
// call example numstr2string("12.3456", "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(strval, System.Globalization.NumberStyles.Number)) retstr = double.Parse(strval).ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
public static string number2string(double numval, string nofdec)
// conversion from numeric value into string in USER CULTURE NUMBER FORMAT!
// call example number2string(12.3456, "0.00") returns "12.34"
{
string retstr = "";
if (Globals.isPositiveNumeric(numval.ToString(), System.Globalization.NumberStyles.Number)) retstr = numval.ToString(nofdec);
else retstr = Globals.safeval.ToString(nofdec);
return retstr;
}
}
// Other Your_App_Namespace content
}
// This the way how to use those functions in any of your app pages
// function to call when TextBox GotFocus
private void textbox_clear(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// save original value
Globals.safeval = double.Parse(txtbox.Text);
txtbox.Text = "";
}
// function to call when TextBox LostFocus
private void textbox_change(object sender, System.Windows.RoutedEventArgs e)
{
TextBox txtbox = e.OriginalSource as TextBox;
// text from textbox into sting with checking and string format
txtbox.Text = Globals.numstr2string(txtbox.Text, "0.00");
}

For Email Validation use the following Regex Expression as below in Lost Focus event of the Textbox.
Use System.Text.RegularExpression Namespace for Regex.
Regex emailExpression = new Regex(#"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
and then check it by using below code
if (emailExpression.IsMatch(textbox.Text))
{
//Valid E-mail
}

For PhoneNumber Validation use the following code in PreviewTextInput event of the Textbox.
private void PhoneNumbeTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
}
private bool AreAllValidNumericChars(string str)
{
bool ret = true;
if (str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeSign |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NegativeInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.NumberGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentDecimalSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PercentGroupSeparator |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PerMilleSymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveInfinitySymbol |
str == System.Globalization.NumberFormatInfo.CurrentInfo.PositiveSign)
return ret;
int l = str.Length;
for (int i = 0; i < l; i++)
{
char ch = str[i];
ret &= Char.IsDigit(ch);
}
return ret;
}

Related

How to check if Parse(args) is true or false

I have code that is not throwing any error. I have used NDesk option set and added 2 string Parameters. I can see it has pulled correct names in args. But when I uses parse(args) it is not throwing an error. So I am assuming it is working.
I am trying to check if p(args) is true or false. But I can not use bool expressions to List<string>.
Any help how I can accomplish that. I want execute function if parse has correct arguments.
My code is like this
private static Regex fileNamePattern = new Regex(#"^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//missing method name
{
string inputFile;
string outputFile;
var p = new OptionSet() {
{"i"," pdf file",v=>inputFile=v},{"o","index file with kws",v=>outputFile=v},
};
Console.WriteLine($"args length: {args.Length}");
Console.WriteLine($"args 0: {args[0]}");
Console.WriteLine($"args 1: {args[1]}");
p.Parse(args); //I would like to use this if(parse(args))
{
}
//
}
private static void UpdateImportIndexFile(string inputFile, string outputFile)
{
using (var dip = File.CreateText(outputFile))
{
var match = fileNamePattern.Match(Path.GetFileName(MainFilePath));
if (match.Success)
{
//create text file (outputfile);
}
}
}
Since p is an instance of a class and the parse method does not support a return to emulate in a sense the functionality of a TryParse wrap your parse in a try block
try{
val = p.Parse(args);
}catch(OptionException e){
//if false
}
For more information http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html#M:NDesk.Options.OptionSet.Parse(System.Collections.Generic.IEnumerable{System.String})

How can I set and send a language on a device with Speechsynthezier? (Windows.Media.Speechsynthesis)

I'm a noob when it comes to programming, but I would like to make a Language Request-Handler where I get an array (Syntax: say language text), split it up,set the device language on the language give to me and let the device speak the text given. I couldn't really find anything about setting a language on a device.
I'm doing an UWP-Project, so I can only use the Windows.Media.Speechsynthezier.
This is my (unfinished!) code at the moment:
//public class LanguageRequestHandler
string _request;
SpeechSynthesizer synth;
private SpeechSynthesizer _synth;
public LanguageRequestHandler( string request)
{
_request = request;
_synth = new SpeechSynthesizer();
var voice = SpeechSynthesizer.AllVoices.SingleOrDefault(i => i.Gender == VoiceGender.Female) ?? SpeechSynthesizer.DefaultVoice;
_synth.Voice = voice;
}
//That should be only a check if the command send to me has the right invocation
public string GetResponse()
{
string response = "invalid command";
string[] args = _request.Split(' ');
if (args[0] == "say")
{
response = CheckLanguage(args[1]);
}
return response;
}
//Here I want to check what language is requested and I actually wanted to set the langauge the device should speak (but as you know by it looks, it is unfinished)
public string CheckLanguage(string language)
{
string response = "No language selected";
string[] args = _request.Split(' ');
if (language == "spanish")
{
}
else if(language == "english")
{
}
else if (language == "german")
{
}
else if (language == "french")
{
}
return language;
}
//Here I'm splitting the Text give to me and putting it together to a sentence that should be later on translated
public string Text(string text)
{
string response = "No text given to translate";
string[] args = _request.Split(' ');
for (int i = 2; i < args.Length; i++)
{
response += args[i] + " ";
}
return text;
}
//Lastly I'm trying to set the volume of the device and synthesis from text to speech which should be streamed to the device and let it speak
public async void Talk(string message)
{
MediaPlayer mp = new MediaPlayer { Volume = 100 };
var stream = await _synth.SynthesizeTextToStreamAsync(message);
mp.Source = MediaSource.CreateFromStream(stream, stream.ContentType);
mp.Play();
}
You could open the 'Windows Settings -> Time& Language -> Language -> Add a language -> Select one language and click the Options button -> Click the Download button below the Speech'.
After that, go to the Speech on the left menus and set the speech language.
I found out that I need to add the Language.Contains()Function to set or change a language. It should be noted that you need to insert a BCP47 Code for the desired language (Example:
i.Language.Contains("fr-FR") for French)
"var voice = SpeechSynthesizer.AllVoices.SingleOrDefault(i => i.Gender == VoiceGender.Female && i.Language.Contains(_request)) ?? SpeechSynthesizer.DefaultVoice;"
Since I found a solution to this problem, I somehow need to split the _request given to me (since the syntax is "say ") and just give it the the BCP47 Code in it (thats why I made the method Checklanguage, it should take it out of the array and put the code in it)

normalizing input string before searching through List c#

I am creating a multi form application which has a series of validation test before the user can save the form. One of those validation functions needs evaluate if the user has entered certain keywords, such as 'Unkown', 'TBA', 'N/A'.I need to begin by normalizing the input string, to strip all unwanted characters such as Whitespace, and extra casing such as 'UNkown', 'tBA'. This then needs to be checked against my list.
This is my current method however my regex doesn't normalize my input string correctly and will pass validation if there is a space in-front of the word
public bool useUnkownEntity(string strTest)
{
Regex rgx = new Regex(#"^[a-zA-Z]");
List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/a"};
useUnkownEntity(rgx.Replace(strTest, ""));
if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
{
MessageBox.Show("please refre to the unkown ENtity within");
return false;
}
return true;
}
My desired result be false if any of the desired words are found iregardless if they are not a exact match. What would be the best approach, to capture all possibilities a user may enter to get passed validation.
This is the event I am calling the method from
private void txt_SurName_Validating(object sender, CancelEventArgs e)
{ // Convert User input to TitleCase
if (useUnkownEntity(txt_SurName.Text))
{
return;
}
if (string.IsNullOrWhiteSpace(txt_SurName.Text))
{
epSurname.Clear(); _IsValid = true;
}
else if (util.IsAllLetters(txt_SurName.Text))
{
epSurname.Clear(); txt_SurName.Text = util.ToTitle(txt_SurName.Text); _IsValid = true;
}
else
{
epSurname.SetError(txt_SurName, "InValid Surname"); _IsValid = false;
}
}
This is my answer so far, it ignores casing but not spacing, if I enter a few spaces at the beginning of the word it will fail, just as it will if a / is forgotten on N/A.
public bool useUnkownEntity(string strTest)
{
Regex rgx = new Regex("[^a-zA-Z/s/ ]");
List<string> unkown = new List<string> { "Unkown", "tba", "tbc","N/A"};
strTest = rgx.Replace(strTest, "");
if (unkown.Contains(strTest, StringComparer.OrdinalIgnoreCase))
{
MessageBox.Show("Please refer to the unkown Entity within!!");
return false;
}
return true;
}

How do I ensure that the user entered an email address in a textbox?

How do I ensure that the user of my web form application has entered an email address? I have seen examples using regex and the EmailAddress(), but how can I implement one or the other in the if else statement below?
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100)
{
emailErrorString = "Email: Enter email address. No more than 100 characters.\n\n";
emailString = null;
errorMessage = true;
}
else
{
emailString = emailTextBox.Text;
emailErrorString = null;
}
I tried the following code and it came back true even when I entered an invalid email address "jj#jj. I did not enter ".com, or ,net, or anything like that:
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 ||
IsValid(emailTextBox.Text).Equals(false))
{
emailErrorString = "Email: Enter a valid email address. No more than 100
characters.\n\n"; emailString = null; errorMessage = true;
}
else
{
emailString = emailTextBox.Text; emailErrorString = null;
}
You can make use of MailAddress class, like below:
public bool IsValid(string emailAddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Alternatively,
you can use RegEx (you should be able to find one suitable for validating email address).
This link gives a basic idea of available characters/patterns: Regexlib
I tried using the MailAddress() example and "jj#jj" came back as a valid email. So, I tried the following and it worked perfectly:
///Create a Regular Expression
Regex regEmail = new Regex(#"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?
\^_`{|}~]+)*"
+ "#"
+ #"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
And:
///test the email textbox against the created Regular Expression
if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 ||
!regEmail.IsMatch(emailTextBox.Text))
{
emailErrorString = "Email: Enter a valid email address. No more than
100 characters.\n\n";
emailString = null;
errorMessage = true;
}
else
{
emailString = emailTextBox.Text;
emailErrorString = null;
}
Well, if it could be any kind of e-mail adress, and the code doesn't have to check whether it's valid or not, you could use this code, which is based on this structure:
example#domain.extension
The only thing is to check whether the string contains an # character, a . character, and a valid e-mail domain and extension (com/de/org/...).
public bool CheckAdress(string Adress)
{
if (Adress.IndexOf('#') == -1)//if there are no # characters in the Adress
{
return false;
}
switch (Adress.Substring(Adress.IndexOf('#') + 1, Adress.IndexOf('.') - Adress.IndexOf('#') + 1)//examines the domain between the # and the. characters
{
case "gmail":
case "freemail":
case "citromail":
//... (any valid domain name)
break;
default:
return false;
}
switch (Adress.Substring(Adress.IndexOf('.') + 1, Adress.Length - Adress.IndexOf('.') + 1))//finally examines the extension
{
case "com":
case "de":
case "org":
//... (any valid extension)
break;
default:
return false;
}
//if all of these have not returned false, the adress might be valid, so
return true;
}
This code only works when there's nothing else in the TextBox, just the adress in question.
I know this is a bit long and maybe not the most perfect answer. But this way you can customize, which domains and extensions are accepted by the code, and which are not.
But if you want to check if this e-mail adress exists in reality, I don't think this solution works.
I didn't add the code that throws exception when the length is more than 100, but you can add it anytime.
Hope this helps a bit! :)
Try creating a new System.Net.Mail.MailAddress object. Pass in the Text property of the TextBox you are using for user input as the parameter to this constructor. Wrap this in a Try Catch block. You'll get a FormatException if the address is invalid.

500 error when querying yahoo placefinder with a particular character?

I am using the Yahoo Placefinder service to find some latitude/longitude positions for a list of addresses I have in a csv file.
I am using the following code:
String reqURL = "http://where.yahooapis.com/geocode?location=" + HttpUtility.UrlEncode(location) + "&appid=KGe6P34c";
XmlDocument xml = new XmlDocument();
xml.Load(reqURL);
XPathNavigator nav = xml.CreateNavigator();
// process xml here...
I just found a very stubborn error, that I thought (incorrectly) for several days was due to Yahoo forbidding further requests from me.
It is for this URL:
http://where.yahooapis.com/geocode?location=31+Front+Street%2c+Sedgefield%2c+Stockton%06on-Tees%2c+England%2c+TS21+3AT&appid=KGe6P34c
My browser complains about a parsing error for that url. My c# program says it has a 500 error.
The location string here comes from this address:
Agape Business Consortium Ltd.,michael.cutbill#agapesolutions.co.uk,Michael A Cutbill,Director,,,9 Jenner Drive,Victoria Gardens,,Stockton-on-Tee,,TS19 8RE,,England,85111,Hospitals,www.agapesolutions.co.uk
I think the error comes from the first hyphen in Stockton-on-Tee , but I can't explain why this is. If I replace this hypen with a 'normal' hyphen, the query goes through successfully.
Is this error due to a fault my end (the HttpUtility.UrlEncode function being incorrect?) or a fault Yahoo's end?
Even though I can see what is causing this problem, I don't understand why. Could someone explain?
EDIT:
Further investigation on my part indicates that the character this hypen is being encoded to, "%06", is the ascii control character "Acknowledge", "ACK". I have no idea why this character would turn up here. It seems that differrent places render Stockton-on-Tee in different ways - it appears normal opened in a text editor, but by the time it appears in Visual Studio, before being encoded, it is Stocktonon-Tees. Note that, when I copied the previous into this text box in firefox, the hypen rendered as a weird, square box character, but on this subsequent edit the SO software appears to have santized the character.
I include below the function & holder class I am using to parse the csv file - as you can see, I am doing nothing strange that might introduce unexpected characters. The dangerous character appears in the "Town" field.
public List<PaidBusiness> parseCSV(string path)
{
List<PaidBusiness> parsedBusiness = new List<PaidBusiness>();
List<string> parsedBusinessNames = new List<string>();
try
{
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
bool first = true;
while ((line = readFile.ReadLine()) != null)
{
if (first)
first = false;
else
{
row = line.Split(',');
PaidBusiness business = new PaidBusiness(row);
if (!business.bad) // no problems with the formatting of the business (no missing fields, etc)
{
if (!parsedBusinessNames.Contains(business.CompanyName))
{
parsedBusinessNames.Add(business.CompanyName);
parsedBusiness.Add(business);
}
}
}
}
}
}
catch (Exception e)
{ }
return parsedBusiness;
}
public class PaidBusiness
{
public String CompanyName, EmailAddress, ContactFullName, Address, Address2, Address3, Town, County, Postcode, Region, Country, BusinessCategory, WebAddress;
public String latitude, longitude;
public bool bad;
public static int noCategoryCount = 0;
public static int badCount = 0;
public PaidBusiness(String[] parts)
{
bad = false;
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Replace("pithawala", ",");
parts[i] = parts[i].Replace("''", "'");
}
CompanyName = parts[0].Trim();
EmailAddress = parts[1].Trim();
ContactFullName = parts[2].Trim();
Address = parts[6].Trim();
Address2 = parts[7].Trim();
Address3 = parts[8].Trim();
Town = parts[9].Trim();
County = parts[10].Trim();
Postcode = parts[11].Trim();
Region = parts[12].Trim();
Country = parts[13].Trim();
BusinessCategory = parts[15].Trim();
WebAddress = parts[16].Trim();
// data testing
if (CompanyName == "")
bad = true;
if (EmailAddress == "")
bad = true;
if (Postcode == "")
bad = true;
if (Country == "")
bad = true;
if (BusinessCategory == "")
bad = true;
if (Address.ToLower().StartsWith("po box"))
bad = true;
// its ok if there is no contact name.
if (ContactFullName == "")
ContactFullName = CompanyName;
//problem if there is no business category.
if (BusinessCategory == "")
noCategoryCount++;
if (bad)
badCount++;
}
}
Welcome to real world data. It's likely that the problem is in the CSV file. To verify, read the line and inspect each character:
foreach (char c in line)
{
Console.WriteLine("{0}, {1}", c, (int)c);
}
A "normal" hyphen will give you a value of 45.
The other problem could be that you're reading the file using the wrong encoding. It could be that the file is encoded as UTF8 and you're reading it with the default encoding. You might try specifying UTF8 when you open the file:
using (StreamReader readFile = new StreamReader(path, Encoding.UTF8))
Do that, and then output each character on the line again (as above), and see what character you get for the hyphen.

Categories