How to check if a textbox starts with numeric value - c#

In Windows forms C#, I want to check if a textbox I made starts with a numeric value, then if it does I want to insert the minus (-) sign at the beginning to change the number to negative, I found a way but it's too time wasting, here's my code:
if (richTextBox1.Text.StartsWith("1") || richTextBox1.Text.StartsWith("2") #until richTextBox1.Text.StartsWith("9"))
{
richTextBox1.Text.Insert(0, "-");
}
So I was asking, if there's a shorter way to replace that code?

if (Char.IsNumber(richTextBox1.Text[0]))...
You should also add some checks around it to make sure there's text.

Using regex:
if (Regex.IsMatch(richTextBox1.Text, #"^\d"))
Matches a digit (0-9) at the start of the string.
Or a direct replace:
richTextBox1.Text = Regex.Replace(richTextBox1.Text, #"^\d", "-$&");

Checking if the first character of a text is a number can be done in single line, using Char.IsNumber() function as follows:
if ( Char.IsNumber( stringInput, 0) ) {
// String input begins with a number
}
More information:
https://learn.microsoft.com/en-us/dotnet/api/system.char.isnumber

Many good answer's already here, another alternative is if you want culture support give this a try...
public static bool IsNumber(char character)
{
try
{
int.Parse(character.ToString(), CultureInfo.CurrentCulture);
return true;
}
catch (FormatException) { return false; }
}
You can call it like:
if ( IsNumber(richTextBox1.Text[0]))

Related

How can I check if a string follows the pattern of american currency?

I'm working on a problem that wants me to get a string input from a user, run it through a method which will check every character to see if it follows the pattern of American currency. It has to be a string that goes into the method. the amount can be any where from 1 dollar to a thousand but must have the format entered as $x.xx, $xx.xx, $xxx.xx, as long as the user enters an amount that is consistent with the above formats then my program should output that its "valid" anything else would be a "invalid format" output. first character must be the '$' and I cannot use regex.
I get the user input and then validate it with .NullOrWhiteSpace. and then send the string value holding the user input down to my created method. from this point I have no idea how to continue. I've tried .ToCharArray, I have also tried making a long and complicated if statement and I have researched for a few hours now but can't find a solid way to write this out.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter amount between $1.00 and $1000.00");
string valueUS = Console.ReadLine();
while (string.IsNullOrWhiteSpace(valueUS))
{
Console.WriteLine("Please enter in an amount");
valueUS = Console.ReadLine();
}
currencyChecker(valueUS);
}
public static string currencyChecker(string currencyString)
{
char[] currencyArray;
currencyArray = currencyString.ToCharArray();
for (int i = 0; i < currencyArray.Length; i++)
{
if (currencyArray[0] == '$')
{
}
}
return currencyString;
the method below should check every character entered by the user and verify that it matches the above described pattern for American currency and output that its "valid" anything else should be reported back as "invalid"
Usually, you would use a regular expression for something like this.
A simple regex for this would be ^\$\d+.\d\d$. Basically, it means the string should start with a $ sign, have at last one digit, a dot, and two more digits.
However, this can be done without regular expressions, and since it seems like a homework task, I'll give you a nudge in the right direction.
So you need to test the string starts with $, the char 3rd from the right is a ., and everything else are digits.
Your method should return a bool indicating valid / invalid results - so you should do something like this:
static bool IsCurrency(string currency)
{
// Check if the string is not null or empty - if not, return false
// check if the string is at least 5 chars long, since you need at least $x.xx - if not, return false
// Check if the first char is $ - if not, return false
// Check if the 3rd char from the end is . - if not, return false
// check if all the other chars are digits - if not, return false
// If all checks are valid -
return true;
}
Note that the order of the tests is critical, for instance if you check the 3rd digit from the right is a . before you check you have at least 5 digits, you might attempt to check a string that is only 2 digits long and get an exception.
Since this is (probably) homework I'm going to leave the code-writing part for you, so you would actually learn something from this.

Verify empty field Selenium C#

I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}

Complex string compare logic

I need help with some complex (for me anyway as I not too experienced) string comparison logic. Basically, I want to validate a string to make sure it matches a format rule. I am using C#, targeting .NET 4.5.2.
I am trying to work with an API which gives me the expected format of the string this way:
1:420+4:9#### (must have “420” starting in position 1 AND have a “9” in position 4 AND have numeric digits in positions 5-8
2:Z+14:&&+20:10,11,12 (must have a “Z” in position 2 AND and alpha letters in positions 14, 15 AND have either “10”, “11”, or “12” starting in position 20
Legend:
":" = position/valuelist separator
"," = value separator
"+" = test separator
"#" = numeric digit-only wildcard
"&" = alpha letter-only wildcard
Given this, my first thought is to do a series of substrings and splits of the input string and then do compare on each section? Or, I could do a for loop and iterate through each character one by one until I hit the end of the length of the input string.
Let's assume in this case that the input string is something like "420987435744585". Using rule number one, I should get a pass on this since the first three are 420, position 4 is a 9 and the next 5-8 are numeric.
So far, I have created a method that returns a bool if I pass/fail validation. The input string is passed in. I then started to split on + or - to get all of the and or not sections and then split on comma to get the groups of rules. But this is where I am stuck. It seems like it should be easy and maybe it is but I just can't seem to wrap my head around it and I am thinking I am going to end up with a ton of arrays, foreach loops, if statements, etc... Just to validate and return true/false if the input string matches my format.
Can somebody please assist and give some guidance?
Thank you!!!!
The best way to handle these conditions would be using Regular Expressions (Regex). At first, you may find it a bit complicated, but it's worth to put time on learning it to handle all types of string patterns in a simple non-verbose way.
You can start with these tutorials :
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial
http://www.tutorialspoint.com/csharp/csharp_regular_expressions.htm
And use this one as a reference :
https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
I think the best way is a custom function, it will be faster than RegEx, and it would be a lot of manual work to convert that format to RegEx.
I've made a start at the validation function, and it's testing ok for the samples you provided.
Here is the code:
static bool CheckFormat(string formatString, string value)
{
string[] tests = formatString.Split('+');
foreach(string test in tests)
{
string[] testElement = test.Split(':');
int startPos = int.Parse(testElement[0]);
string patterns = testElement[1];
string[] patternElements = patterns.Split(',');
foreach(string patternElement in patternElements)
{
//value string not long enough, so fail.
if(startPos + patternElement.Length > value.Length)
return false;
for (int i = 0; i < patternElement.Length; i++)
{
switch(patternElement[i])
{
case '#':
if (!Char.IsNumber(value[i]))
return false;
break;
case '&':
if (!Char.IsLetter(value[i]))
return false;
break;
default:
if(patternElement[i] != value[i])
return false;
break;
}
}
}
}
return true;
}
The dotnet fiddle is here if you want to play with it: https://dotnetfiddle.net/52olLQ.
Good luck.

Regex does not work to filter TextBox characters in WinForms

I want to create a TextBox (WinForms) that only accepts possitive or negative numbers and any number of character 'k' at the end, I think the pattern is ^-?[0-9]+k*$
I want to prevent the user from writing any character that does not match withe that expression. This is the class that I have implemented:
public class NumTextBox : TextBox {
private Regex regex;
public NumTextBox() : base() {
regex = new Regex(#"^-?[0-9]+k*$");
}
protected override void OnKeyPress(KeyPressEventArgs e) {
String s = Text + e.KeyChar; // current text + new character
if (!regex.Match(s).Success) {
e.Handled = true;
} else {
e.Handled = false;
}
base.OnKeyPress(e);
}
}
}
With that, the TextBox does not allow you to write characters at the beginning of the text, but it allows you to write them after some digit, I mean:
asd -> Not allowed
123asd -> allowed, this shouldn't be allowed
I have also tried to add the end character to s but it neither works.
Edit:
I have seen in the debugger that the string s has the new character at the end.
Edit 2
Why don't you just TryParse the TextBox's Text value?
Because I want to prevent the user to be able to write not allowed characters, according to the regex.
The code has some other problems too :
1. It should not work if user start to enter a negative number because (-) itself is not matched.
2. what if the text is 123 and user click between 1 and 2 and then press k ?( keypress is not a good place for this)
1: I think you are right, but I prefer to solve this problem now and take care of that later.
2: Letter 'k' shouldn't be allowed between digits, only at the end of the number.
If you debug your code, is the regex matching and stepping into e.Handled=true, or not? Also, OnTextChanged might be a better method to override.
If I debug the code, the regex matchs (says it's correct) wrong strings (f.e. 123asd), so it doesn't step into e.Handled = true.
I think you are referring to override OnTextChanged and delete the last char written if it doesn't match with the regex, don't you? In that case, a problem that I've seen is that the text pointer returns to the beginning.
I believe your issue is here:
string s = Text + e.KeyChar; // current text + new character
The problem is that it appends the new character, regardless of the cursor position. This means if you go to the beginning of the string and type in 'k,' then Handled does not fire because you said + 'k', which is fine, per the regex.
It's far from perfect, but you could handle the OnTextChanged in the following way that would meet your needs. I tested it only briefly, but it appears to yield the desired behavior, to the best of my understanding.
protected override void OnTextChanged(EventArgs e)
{
if (string.IsNullOrEmpty(this.Text))
return;
int pos = this.SelectionStart;
if (!regex.IsMatch(Text))
{
this.Text = _OldValue;
this.SelectionStart = pos > 0 ? pos - 1 : pos;
}
else
_OldValue = this.Text;
base.OnTextChanged(e);
}
You can see I put in a hack to address the cursor returning to the beginning of the string, which you addressed in your post or comment.
What you can do is to check which key is pressed and if its the correct one then you should add it
for your example is this:
int temp;
if(int.TryParse(e.KeyChar,out temp) || e.KeyChar == '-' || e.KeyChar == 'k')
{
//code
}

Check for special characters (/*-+_#&$#%) in a string?

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-]+$

Categories

Resources