normalizing input string before searching through List c# - 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;
}

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})

c# razor functions in external file

I have a function on my cshtml page that checks if an entered email is valid, it works as it should, however i now need to move it into an external file, with all the other functions I've created, I cant seem to find any information on this, can anyone tell me what file extension the file should have? I know it needs to go into the App_Code folder, am I supposed to do anything special to my function? and how do I call it on my web page? My lecturer literally has no notes covering this.
bool IsEmail(string email) {
//declare the return variable
bool rst = false;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
// does the string follow the regex structure?
System.Text.RegularExpressions.Match match = regex.Match(email);
//if yes
if (match.Success){
rst = true;
} else {
rst = false;
}
return rst;
}
Thanks in advance
In a new file in App_Code:
public static class GodObject {
public static bool IsEmail(string email) {
//declare the return variable
bool rst = false;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
// does the string follow the regex structure?
System.Text.RegularExpressions.Match match = regex.Match(email);
//if yes
if (match.Success){
rst = true;
} else {
rst = false;
}
return rst;
}
}
Then you can reference GodObject.IsEmail(...) from just about anywhere.
This is probably what your prof is after, however, there are far better ways to approach this validation.

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.

Asp.Net custom validation control not showing error messages

The following code is used to validate when form submit button is hit, but I am not getting the wanted result back.
It should display the error messages but they are not being displayed what am I doing wrong?
The custom validator validates passwords, it should change the error message based on the which errors occur:
Password is blank
Password is invalid
Passwords do not match
Only one error should show at a time so I wrote this custom validtor in .ascx.cs:
protected void cvPasswordValidation_ServerValidate(object source, ServerValidateEventArgs args)
{
bool IsPasswordBlank = false;
bool IsPasswordValid = false;
cvPasswordValidation.IsValid = false;
// If password is blank then IsValid is false, show blank password errors.
if (String.IsNullOrEmpty(args.Value))
{
//args.IsValid = false;
IsPasswordBlank = true;
//Show blank password error depending on which box is empty.
if (String.IsNullOrEmpty(txtPassword.Text))
{
cvPasswordValidation.ErrorMessage = "You must enter password";
}
else
{
cvPasswordValidation.ErrorMessage = "You must confirm password";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If password is not valid format then IsValid is false, show invalid format errors.
if (!Regex.IsMatch(args.Value, RegexHelper.ValidPassword))
{
IsPasswordValid = true;
//Show invalid format errors, if password is not blank
if (IsPasswordBlank == false)
{
cvPasswordValidation.ErrorMessage = "<b>Current password</b> not in correct format. Your password must contain 6 - 12 characters with a combination of numbers and letters.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
// If passwords do not match then IsValid is false, show do not match errors.
bool areEqual = String.Equals(txtPassword.Text, txtConfirmPassword.Text, StringComparison.Ordinal);
if (areEqual == false)
{
//Show do not match errors is password is not blank and is not invalid format
if (IsPasswordBlank == false && IsPasswordValid == false)
{
cvPasswordValidation.ErrorMessage = "Your passwords do not match.";
}
cvPasswordValidation.IsValid = false;
}
else
{
cvPasswordValidation.IsValid = true;
}
}
and the .ascx:
<asp:TextBox runat="server" ID="txtPassword" MaxLength="12" autocomplete="off" TextMode="Password" ValidationGroup="vgOnlineDetails"></asp:TextBox>
<asp:CustomValidator ID="cvPasswordValidation"
runat="server"
display="Dynamic"
OnServerValidate="cvPasswordValidation_ServerValidate"
ControlToValidate="txtPassword"
ValidationGroup="vgOnlineDetails">
</asp:CustomValidator>
You need to set ValidateEmptyText = true to validate empty fields.
You shoul use return after assignment to IsValid property. Condider situation when you do not specify password at all. If you do not specify return after assignment all three if statements will be executed. In last if areEqual variable will be true because two empty strings are equal and cvPasswordValidation.IsValid = true; will be executed. In this case your text boxes will be valid.

Validation of textbox input in 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;
}

Categories