Validating a numeric textbox - c#

I'm trying to validate a textbox to check that it has a phone number type value entered.
The problem I'm having is that even when the entry is for example: "blah" in these text boxes the Regex is still returning false and no error message is shown.
Regex staffNumVal = new Regex(#"^[a-z]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
MessageBox.Show("Please enter a numeric value");
}
Is there a better way to do this that I'm missing? Thanks.

Instead of
Regex staffNumVal = new Regex(#"^[a-z]+$");
Use
Regex staffNumVal = new Regex(#"^[0-9]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
//Valid
}
else
{
MessageBox.Show("Please enter a numeric value");
}

Regex staffNumVal = new Regex(#"^\d*$");

Try it like so
int value;
if (int.TryParse(txtStaffHPhone.Text, out value))
{
// it's a valid integer
}

Regex regex = new Regex(#"^\d$");
Refer for Details: Regex for numbers only

Your RegEx does not do what you expect it.
I think the '^' is misplaced. It should be: #"[^a-z]+$".
But even that is wrong, since it accepts things like &.
You can test at: http://regexhero.net/tester/
But I think you'll be better served with a MaskedTestBox. Have you tried that?

Import Microsoft.VisualBasic and use it!
if (Microsoft.VisualBasic.Information.IsNumeric("5"))
{
//Do Something
}

Related

Is there a method in c# to check if a string is a valid hexadecimal number?

I wanted to add a manual hexadecimal input for a C# repository of mine, I had no way of verifying if the user's input was a legitimate ARGB hexadecimal value the user had entered into the textbox or if it was a garbage hexadecimal number. Does anyone have a potential solution to this?
You can just use regex:
string pattern = #"^0[xX][0-9a-f]{8}$";
string input = "0x1a2b3C";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success)
{...}
So, I did a very inefficient method, I started off by making a pastebin with every single valid ARGB hex code, I then wrote the following:
WebClient Checker = new WebClient();
string List = Checker.Downloadstring("https://pastebin.com/raw/link");//link would be the pastebin
string Input = this.TextBox.Text;
if (List.Contains(Input))
{
//submit write file code here
}
else
{
System.Windows.Messagebox.Show("The Input Was Not Valid! Please Input A Valid ARGB Code!", "Error!");
}
This method ended up working for me. It isn't recommended but does the job right.

How do I make regex properly validate the information?

I've been given the task to make a textbox where you enter your personal code (something we in Latvia use). I need it to be validated before saving the information. For validation I've been using Regex but so far got no result.
Our personal code is like this : XXYYZZ-ABCDE, where
XXYYZZ is date format as in DAYMONTHYEAR and ABCDE are random numbers.
if (per_kods.Text.Trim() != string.Empty)
{
mRegxExpression = new Regex("${day}-${month}-${year}-#####$");
if (!mRegxExpression.IsMatch(per_kods.Text.Trim()))
{
label7.Text = "";
}
else
{
label7.ForeColor = Color.Red;
label7.Text = "Personas kods ievadīts nepareizi!";
pareizi = false;
}
}
this currently is my code. It basically enables a label above the textbox pointing out that the information entered is wrong. If the information is right, the label continues to be disabled. But right now the new Regex part is a problem. I know it might seem totally wrong, but I've just started learning Regex and don't know what's wrong and what's right.
If you don't care about date validation (so for example 31st of February will be accepted, you can do
new Regex(#"^(0[1-9]|[1-2]\d|3[0-1])(0[1-9]|1[0-2])(\d{2})-(\d{5})$");
If you want to understand what this string means, take a look at the MSDN reference.
Now for date validation, so filtering out dates like 310298 that don't exist, I'd recommend you do it manually afterwards - regex is not the best tool for such logic-validation.
EDIT:
You can accomplish that using DateTime.TryParse.
DateTime resultDateTime;
var isValid = DateTime.TryParse(string.Format("{0}-{1}-{2}", 2010, 2, 31), out resultDateTime);
// isValid is false, because 31st of February 2010 does not exist.
var isValid = DateTime.TryParse(string.Format("{0}-{1}-{2}", 2010, 2, 27), out resultDateTime);
// isValid is true, and resultDateTime has been set to 27-2-2010.
Note that DateTime.TryParse is culture sensitive. Depending on the target culture you might need to change the input string. See MSDN reference for TryParse.
EDIT2:
So to connect this with your existing code:
mRegxExpression = new Regex(#"^(0[1-9]|[1-2]\d|3[0-1])(0[1-9]|1[0-2])(\d{2})-(\d{5})$");
var match = mRegxExpression.Match(per_kods.Text.Trim()));
if(!Validate(match))
{
// Handle invalid.
}
else
{
// Handle valid.
}
Where Validate would be:
private static bool Validate(Match match)
{
if(!match.Success)
{
return false;
}
var day = match.Groups[1].ToString();
var month = match.Groups[2].ToString();
var year = match.Groups[3].ToString();
return DateTime.TryParse($"{day}-{month}-{year}", out _);
}
Because our regex begins with ^ and ends with $, there will be always at most one match. The Success property tells us whether there was any match at all, and later the Groups property gives us the capture groups. Groups[0] will be the entire matched string, and then every next one will be the substring that matches one of the parentheses enclosed groups from regex - so the first one is (0[1-9]|[1-2]\d|3[0-1]) which represents days, the second will be months, and so on. Then we just check if the date is valid (again, culture sensitive!). Also, we can neatly use the C#7 discard syntax (_) for the out parameter, as we don't need it.
You can get help from the code below to check validation.
public bool CheckValidation(string input)
{
input = input.Trim();
if (input == string.Empty) return false;
var mRegxExpression = new Regex("^([0-2][0-9]|(3)[0-1])(((0)[0-9])|((1)[0-2]))\\d{2}(\\-)\\d{5}$");
return mRegxExpression.IsMatch(input);
}

Issue with Validating Phone number on user input,Int to large c#

Overview of Project:
I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.
public static bool numValidation(string strNum)
{
if (!string.IsNullOrWhiteSpace(strNum))
{
int temp;
if (int.TryParse(strNum, out temp))
{
Console.WriteLine("Phone Number is a valid input: " + temp);
return true;
}
else
{ Console.WriteLine(temp + "Is not Valid input!!"); }
}
return false;
}
At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers
I suggest that you use a regular expresion to validate the input in your case
public static bool numValidation(string strNum)
{
Regex regex = new Regex(#"^[0-9]+$");
return (regex.IsMatch(strNum)) ;
}
Parsing a string and not using that value is not really needed.
For more details checkout this answers - Regex for numbers only
From Mauricio Gracia Gutierrez answer
I suggest that you use a regular expresion to validate the
input in your case
public static bool numValidation(string strNum) {
Regex regex = new Regex(#"^[0-9]+$");
return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed.
For more details checkout this answers - Regex for numbers only
You could enhance the expression to check the length of the number:
Between 5 and 10 digits:
Regex regex = new Regex(#"^[\d]{5,10}+$");
Max 10 digits:
Regex regex = new Regex(#"^[\d]{10}+$");
At least 5 digits:
Regex regex = new Regex(#"^[\d]{5,}+$");

Regex not working in c# wpf

I want to check if entered name contains only alpha numeric data or _ or space.
Like a file name.
this is my function
public bool IsAlphaNumeric(String strToCheck)
{
bool res;
Regex objAlphaNumericPattern = new Regex("^[a-zA-Z0-9_]+$");
res=objAlphaNumericPattern.IsMatch(strToCheck);
return res;
}
but it returns false even for strings like "abc def"
i.e . it allows only spaceless strings like "abc12"..
can you give the correct code..or what is wrong in my code
Regex objAlphaNumericPattern = new Regex("^[a-zA-Z0-9_\\s]+$");
this works fine for me.
^[a-zA-Z0-9_\s]+$
or you can also use
^[a-zA-Z0-9_ ]+$
Add \s to include space as well.

Allow user to only input text?

how do I make a boolean statement to only allow text? I have this code for only allowing the user to input numbers but ca'nt figure out how to do text.
bool Dest = double.TryParse(this.xTripDestinationTextBox.Text, out Miles);
bool MilesGal = double.TryParse(this.xTripMpgTextBox.Text, out Mpg);
bool PriceGal = double.TryParse(this.xTripPricepgTextBox.Text, out Price);
Update: looking at your comment I would advise you to read this article:
User Input Validation in Windows Forms
Original answer: The simplest way, at least if you are using .NET 3.5, is to use LINQ:
bool isAllLetters = s.All(c => char.IsLetter(c));
In older .NET versions you can create a method to do this for you:
bool isAllLetters(string s)
{
foreach (char c in s)
{
if (!char.IsLetter(c))
{
return false;
}
}
return true;
}
You can also use a regular expression. If you want to allow any letter as defined in Unicode then you can use this regular expression:
bool isOnlyLetters = Regex.IsMatch(s, #"^\p{L}+$");
If you want to restrict to A-Z then you can use this:
bool isOnlyLetters = Regex.IsMatch(s, #"^[a-zA-Z]+$");
You can use following code in the KeyPress event:
if (!char.IsLetter(e.KeyChar)) {
e.Handled = true;
}
You can use regular expression, browse here: http://regexlib.com/
You can do one of a few things.
User Regular Expression to check that the string matches your concept of 'Text' only
Write some code that checks each character against a list of valid characters. Or even use char.IsLetter()
Use the MaskedTextBox and set a custom mask to limit input to text only characters
I found hooking up into the text changed event of a textbox and accepting/rejecting the changes an acceptable solution. To "only allow text" is a rather vague definition, but you may as well check if your newly added text (the next char) is a number or not and simply reject all numbers/disallowed characters. This will make users feel they can only enter characters and special characters (like dots, question marks etc.).
private void UTextBox_TextChanged(object sender, EventArgs e)
{
string lastCharacter = this.Text[this.Text.Length-1].ToString();
MatchCollection matches = Regex.Matches(lastCharacter, "[0-9]", RegexOptions.None);
if (matches.Count > 0) //character is a number, reject it.
{
this.Text = Text.Substring(0, Text.Length-1);
}
}

Categories