Allow user to only input text? - c#

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

Related

Regex for string without spacial characters or spaces [duplicate]

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

My regex match positive real numbers doesn't work

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

How to differentiate text and change align accordingly

I have a requirement, I have a textfield which I'm fetching the data from database. It may be in Arabic or in English. I want to differentiate it dynamically and change alignment accordingly. ie, if the text is in Arabic it should be from right to left else left to right.
You can said that the text is in arabic, if count of arabic characters is more than count of english characters.
You can determine it using character classes in regular expression
public bool IsArabic(this string input)
{
var isArabic = Regex.Matches(input, "\\p{IsArabic}");
var isLatin = Regex.Matches(input, "\\p{IsBasicLatin}");
if (isArabic == null)
return false;
if (isLatin == null)
return true; //suggest that there is no another character types
if (isArabic.Count > isLatin.Count)
return true;
return false;
}
If text contains RTL mark then Windows does it for you.
Otherwise you may simply check for characters (don't forget System.Char represents a code-unit, not a code-point but in this case it's not an issue) in Unicode Arabic Code block:
public bool IsArabic(string text)
{
return Regex.IsMatch(text, "[\u06000-\u06FF]")
}

How to check if the tape starts with special characters

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

String.Equals how does it work?

I have string text="camel", and then I want to check if text contains letter "m", so I loop through it and checking it using:
if (text[i].Equals("m"))
but this never returns me true... why?
Since you are comparing a character with a string this won't work.
Here's some more information on String comparisons
In this case you should use
if(text.Contains("m"))
As mentioned by #MattGreer, you're currently comparing a character and a string. This is because of the delimiter you've chosen for your literal, and because text[i] returns a character from a string rather than a substring of that string.
Please note the difference between using string literal delimiters (quote) and character literal delimiters (apostrophe):
if (text[i].Equals('m'))
Also, as others have stated, unless there is some reason you want to iterate through each character, String.Contains() would seemingly serve the intended purpose.
You need to find all occurences of a letter in a text as I understand it:
string text = "camel";
string lookup = "M";
int index = 0;
while ( (index = text.IndexOf(lookup, index, StringComparison.OrdinalIgnoreCase) != -1)
{
// You have found what you looked for at position "index".
}
I don't think that you get it any faster than this.
Good luck with your quest.
The answers has been given to you by Kyle C, so this is how you complete the whole process and I'm gonna use winforms as an example:
private void button1_Click(object sender, EventArgs e)
{
string text = "camel";
if (text.Contains("m") || text.Contains("M"))//also checks for capital M
{
MessageBox.Show("True");
}
}
Miraclessss
Use Contains
You're asking if "camel" is the equivalent of "m" -- which it is not.
"camel" contains "m".

Categories