I'm really new to programming and haven't come across Regex until now, I am looking to restrict textbox input to double class values only and came across this:
`Regex regex = new Regex("[^0-9-]+");
TextP1_TextChanged = regex.IsMatch(TextP1.Text);`
I want to implement into my program and am assuming it occurs under the TextChanged event, but I don't actually have the knowledge to implement regex and so am just looking for any help.
Update
I've implemented TryParse but am looking to accept decimal numbers with or without 0 in front, i.e. 0.234 or .234. My new code is this:
private void TextP1_TextChanged(object sender, EventArgs e)
{
bool isDouble = Double.TryParse(TextP1.Text, out P1);
if(isDouble == false)
{
MessageBox.Show("Text box only accepts positive number values", "Text entered into P1 is invalid", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You could use this regular expression [0-9]*\.[0-9]*. The * means 0-9 can occur 0 to x times.
You could use regexr to test regular expression in a fast way.
Related
So i'm trying to strip data from a string because I have in WPF a "preset" input which looks like __,___, now a user must input something like 30,589, but when a user just gives in 5 or 50, it needs to strip the rest (keeping the ,) to propperly make a float of the input value. The code that I have right now looks like this;
if (inp_km.Text == "__,___")
{
team_results.results[inp_tour_part.SelectedIndex].km =
float.Parse("00,000",
NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("nl-NL")); // Give the new value
}
else
{
team_results.results[inp_tour_part.SelectedIndex].km =
float.Parse(inp_km.Text,
NumberStyles.AllowDecimalPoint,
CultureInfo.GetCultureInfo("nl-NL")); // Give the new value
}
But this code just check wether the input is left blank or not... Could someone help me out?
Edit
So I've included a screen, this is the input lay-out a user gets;
Os you can see, the inputs are 'pre-filled', the content of such an input is a "string", so, let's say, I type into the first input just 5;
Then the value (retreived in C# by input_name.Text) is 5_:__, but that's a "wrong" value and you can't fill in such things, how could I check if there still is a : or _ in the input.
Also, the bottom input is the same, but then it needs to be filled in completely.
So you want to check either the input is in one of the two forms: 12,345 or 12:34.
This can be done using Regex very easily.
static void Main(string[] args)
{
var inputComma = "12,345";
var inputColon = "98:76";
Regex regexComma = new Regex(#"^\d{2},\d{3}$");
Regex regexColon = new Regex(#"^\d{2}:\d{2}$");
var matchComma = regexComma.Match(inputComma);
if (matchComma.Success)
{
Console.WriteLine(inputComma);
}
Console.WriteLine();
var matchColon = regexColon.Match(inputColon);
if (matchColon.Success)
{
Console.WriteLine(inputColon);
}
Console.ReadLine();
}
NOTE:
You haven't quite clarified the valid formats for your input. The above will evaluate to true strictly for 12,345 format if commas are present (i.e., two digits followed by a comma followed by three digits), and for colon, only numbers of the format 12:34 (two digits before and after the colon) only.
You might want to modify your Regex based on your exact criteria.
I am reading from a TextBox in C# and I want to make sure that only real positive values are allowed (including integers).
i.e. 1, 23, 23., 23.0, 23.42, etc.
The Regex I am using is:
[0-9]+\\.?[0-9]*
But C# does only let me type numbers and I can never put a period.
Thank you
Code:
private static readonly Regex rgx_onlyPositiveReals = new Regex("[0-9]+\\.?[0-9]*");
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !IsSamplingRateAllowed(e.Text);
}
private static bool IsSamplingRateAllowed(string text)
{
if(rgx_onlyPositiveReals.IsMatch(text))
{
if(text.Equals(".") || float.Parse(text) <= 0.0)
{
MessageBox.Show("Sampling Rate has to be positive.", "Wrong Sampling Frequency Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
return true;
}
return false;
}
From the looks of things this input box is supposed to only contain the number and no other text; in this case I would avoid the regular expression altogether.
Given that you're parsing the regex match result into a float anyway, it might make more sense to try parsing the input as a float directly which has the added benefits of allowing any valid positive float that can be parsed in the first place, it also allows entering the number in any other valid formats supported by float.Parse/float.TryParse e.g. scientific notation "1E5" == 100000f or commas "1,500" == 1500f (depending on the culture) without any additional effort.
private static bool IsSamplingRateAllowed(string text)
{
float number;
return float.TryParse(text, out number) && number >= 0.0f;
}
Unless this data is being used for some external process as a string with additional restrictions on the format (which seems unlikely and is worth including in the question if that is the case), then if it isn't already, I'd recommend separating this input box from any other information and have users enter the number and only the number directly into the box. If you need to collect other information from the user you can add other input boxes and controls as necessary (which can also simplify validation for other pieces of information).
Give this a try
The pattern is ^[0-9]+\.?[0-9]*
In C# you can prefix your string with # which makes it easier to read a regex. It results in the following:
"\\this \\is \\the \\same" == #"\this \is \the \same"
You can simply use the below Regex
^\d*[.]?\d*$
Demo Fiddle
I need to track to string began with the required letters (Cyrillic or Latin or even any letters). But definitely not with numbers or special characters including space.
For start my task was only hanlde string starts with number but for now also certain characters.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int i;
if (isRoot && (int.TryParse(textBox1.Text.Trim(), out i)))
What should I do for characters?? Use something like this (but in this case I need to make conditions for all characters):
(textBox1.Text.Trim(). StartsWith("%") || textBox1.Text.Trim().StartsWith("-") || ......
)
Is there some better ways?? Coz if you propose to allow only letters then it is a bad idea because it can be given a different language.. So what?
You can use a Regular Expression to handle this functionality.
For example:
This snippet makes sure an input file path is correctly formatted.
// [drive_letter]:\ or \\[server]\ or [drive name]:\
private const string PathPattern = "^[A-z]:[\\\\/]|^\\\\|^.*[A-z]:[\\\\/]";
var matchMaker = new Regex(PathPattern);
var success = matchMaker.Matches(inputPath);
In your case you want to identify different characters and trim them, so you'd identify those strings with a Regex expression then carry out your parsing logic.
This link has a list of all the Regex commands:
http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
I am developing a windows form application in .net c#, All I want to know is how to validate the Indian phone number, if a user inputs in a textbox.
You can make use of Regular expression
e.g.
Regex rx = new Regex(#"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$");
and than you can use rx.IsMatch to validate the input string.
the standard format of Indian mobile phone number is +91 (country code) followed by 10 digits.
+91 XXXXXXXXXX
just check if this is followed. if its a land phone number the check is difficult. oryou might get external websites which can validate the number for you.
All you can do is check for the country code for an exact match. then the rest are all digits and there is 10 of them. no other characters allowed. In india we dont we dont use - to separate between digits
In c# you need a regex that checks for +91 followed by 10 digits
it may also be worth checking for 0091 followed by 10 digits
EDIT
just for completeness sake the following would do (\+91|0091)\d{10}
System.Text.RegularExpressions.Regex expr;
public bool email(string email)
{
expr =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]$");
if (expr.IsMatch(email))
{
return true;
}
else return false;
}
public bool phone(string no)
{
expr = new Regex(#"^((\+){0,1}91(\s){0,1}(\-){0,1}(\s){0,1}){0,1}9[0-9](\s){0,1}(\-){0,1}(\s){0,1}[1-9]{1}[0-9]{7}$");
if (expr.IsMatch(no))
{
return true;
}
else return false;
}
I tried all above mentioned methods, didn't worked out for Me... So I made own Code:-
It will work for SURE:
private void btnValidatePhoneNumber_Click(object sender, EventArgs e)
{
Regex re = new Regex("^9[0-9]{9}");
if(re.IsMatch(txtPhone.Text.Trim()) == false || txtPhone.Text.Length>10)
{
MessageBox.Show("Invalid Indian Mobile Number!!");
txtPhone.Focus();
}
}
upvote if you like it! :)
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);
}
}