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,}+$");
Related
I need to validate a input string based on certain formats i.e
Proj-######## (4 alphabets, 1 Dash and 8 numbers)
OP###### (2 characters, 6 numbers)
Can someone please help me on this?
I tried with the below approach it's working for 1 dash and 8 numbers. but am not geeting how to add code into regerx for allow only 4 charactes.
private static readonly Regex boxNumberRegex = new Regex(#"^\d-\d{8}$");
public static bool VerifyBoxNumber (string boxNumber)
{
return boxNumberRegex.IsMatch(boxNumber);
}
Try this.
\b[a-zA-Z]{4}-\d{6}\b - is for Proj-########
\b[a-zA-Z]{2}\d{6}\b - is for OP######
If you want to learn bulding regular expressions, have a look at this article. Worth reading it.
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial
Question: How can I write this without putting in all the possible cases? If someone gets 4 password requirements one day it will be easy to put in but be very difficult to debug since there will be 4! different ways to work the middle.
How I have it in code:
[RegularExpression("^[A-Za-z0-9!##$]*([A-Za-z][0-9][!##$]|[0-9][!##$][A-Za-z]|[!##$][A-Za-z][0-9]|[!##$][0-9][A-Za-z]|[0-9][A-Za-z][!##$]|[A-Za-z][!##$][0-9])[A-Za-z0-9!##$]*$", ErrorMessage = "The Password value must contain at least one letter, one digit, and one special character.")]
For viewing convenience I broke it so no scrolling is required:
[RegularExpression("^[A-Za-z0-9!##$]*
([A-Za-z][0-9][!##$]|[0-9][!##$][A-Za-z]|
[!##$][A-Za-z][0-9]|[!##$][0-9][A-Za-z]|
[0-9][A-Za-z][!##$]|[A-Za-z][!##$][0-9])
[A-Za-z0-9!##$]*$",
ErrorMessage = "The Password value must contain at least one letter,
one digit, and one special character.")]
As you can see this is 3! possibilities from the middle () separated by | (OR) so from this you can see 4! possibilities would be very difficult to maintain.
Question Requirements: The basic thing I want this RegularExpression in C# to do is require (in no particular order) at least one letter, at least one number, at least one special character !, #, #, or $
One Regex
You can use zero-width positive lookahead assertions (see MSDN's "Regular Expression Language - Quick Reference" - in the Grouping Constructs section) to check for your ANDed password requirements - without having to explicitly cover all the orders in which the required password components may occur:
^(?=.*?[a-zA-Z])(?=.*?[0-9])(?=.*?[!##$]).{3,}$
This works as follows:
(?=.*?[a-zA-Z]) - an alpha character found ahead
(?=.*?[0-9]) - and a number found ahead
(?=.*?[!##$]) - and an allowed special character ahead
.{3,} - three or more characters in total
I have shared a regex fiddle based on this that you might find useful.
Property-Per-Criterion Password Checker
Per #LeffeBrune's comment, you should consider alternatively checking with a dedicated password-checker class that exposes a property per criterion.
For example, here is a quick & dirty PoC in LINQPad 4...
void Main()
{
var passwords = new string[] {"password", "passw0rd", "passw0rd!", "123456", "!##$"};
foreach (var pw in passwords)
{
var checker = new PasswordChecker(pw);
var isValid = checker.IsValid;
Console.WriteLine("Password {0} is {1}valid.", pw, isValid ? "" : "in");
if (!isValid)
{
Console.WriteLine(" Has alpha? {0}", checker.HasAlpha ? "Yes." : "NO!");
Console.WriteLine(" Has number? {0}", checker.HasNumber ? "Yes." : "NO!");
Console.WriteLine(" Has special? {0}", checker.HasSpecial ? "Yes." : "NO!");
Console.WriteLine(" Has length? {0}", checker.HasLength ? "Yes." : "NO!");
}
}
}
public class PasswordChecker
{
public const int MINIMUM_LENGTH = 3;
private string _password;
public PasswordChecker(string password)
{
_password = password;
}
public bool HasAlpha
{
get
{
return Regex.Match(_password, "(?=.*?[a-zA-Z])").Success;
}
}
public bool HasNumber
{
get
{
return Regex.Match(_password, "(?=.*?[0-9])").Success;
}
}
public bool HasSpecial
{
get
{
return Regex.Match(_password, "(?=.*?[!##$])").Success;
}
}
public bool HasLength
{
get
{
return _password.Length >= MINIMUM_LENGTH;
}
}
public bool IsValid
{
get
{
return HasLength && HasAlpha && HasNumber && HasSpecial;
}
}
}
...that produces the following output:
Password password is invalid.
Has alpha? Yes.
Has number? NO!
Has special? NO!
Has length? Yes.
Password passw0rd is invalid.
Has alpha? Yes.
Has number? Yes.
Has special? NO!
Has length? Yes.
Password passw0rd! is valid.
Password 123456 is invalid.
Has alpha? NO!
Has number? Yes.
Has special? NO!
Has length? Yes.
Password !##$ is invalid.
Has alpha? NO!
Has number? NO!
Has special? Yes.
Has length? Yes.
You could take this quick & dirty PoC much further of course, but the benefits of knowing what criterion or criteria failed are hopefully clear.
I am new to regex stuff in C#. I am not sure how to use the regex to validate client reference number. This client reference number has 3 different types : id, mobile number, and serial number.
C#:
string client = "ABC 1234567891233";
//do code stuff here:
if Regex matches 3-4 digits to client, return value = client id
else if Regex matches 8 digts to client, return value = ref no
else if Regex matches 13 digits to client, return value = phone no
I dont know how to count digits using Regex for different types. Like Regex("{![\d.....}").
I don't understand why you're bent on using regular expressions here. A simple one-liner would do, eg. even such an extension method:
static int NumbersCount(this string str)
{
return str.ToCharArray().Where(c => Char.IsNumber(c)).Count();
}
It's clearer and more maintainable in my opinion.
You could probably give it a go with group matching and something along the lines of
"(?<client>[0-9]{5,9}?)|(?<serial>[0-9]{10}?)|(?<mobile>[0-9]{13,}?)"
Then you'd check whether you have a match for "client", "serial", "mobile" and interpret the string input on that basis. But is it easier to understand?
Does it express your intentions more clearly for those reading your code later on?
If the requirement is such that these numbers must be consecutive (as #Corak points out)... I'd still write that iteratively, like so:
/// <summary>
/// returns lengths of all the numeric sequences encountered in the string
/// </summary>
static IEnumerable<int> Lengths(string str)
{
var count = 0;
for (var i = 0; i < str.Length; i++)
{
if (Char.IsNumber(str[i]))
{
count++;
}
if ((!Char.IsNumber(str[i]) || i == str.Length - 1) && count > 0)
{
yield return count;
count = 0;
}
}
}
And then you could simply:
bool IsClientID(string str)
{
var lenghts = Lengths(str);
return lenghts.Count() == 1 && lenghts.Single() == 5;
}
Is it more verbose? Yes, but chances are that people will still like you more than if you make them fiddling with regex every time the validation rules happen to change, or some debugging is required : ) This includes your future self.
I'm not sure if I understood your question. But if you want to get the number of Numerical Characters from a string you can use the following code:
Regex regex = new Regex(#"^[0-9]+$");
string ValidateString = regex.Replace(ValidateString, "");
if(ValidateString.Length > 4 && ValidateString.Length < 10)
//this is a customer id
....
This question already has answers here:
.NET String.Format() to add commas in thousands place for a number
(23 answers)
Closed 9 years ago.
I'm trying to put comma's between long numbers automatically, but so far without success. I'm probably making a very simple mistake, but so far I can't figure it out. This is the code I currently have, but for some reason I'm getting 123456789 as the output.
string s = "123456789";
string.Format("{0:#,###0}", s);
MessageBox.Show(s); // Needs to output 123,456,789
var input = 123456789;
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
If, as per your question, you need to start with a string:
var stringInput = "123456789";
var input = int.Parse(stringInput);
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
You'll possibly also need to take culture into account when parsing/formatting. See the overloads that take an IFormatProvider.
Try this:
string value = string.Format("{0:#,###0}", 123456789);
In your code you are missing the initial { in the format string, and then number formatting options apply to numbers, while your s is a string.
You could convert the string to a number with int.Parse:
int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value);
This should work (you need to pass String.Format() a number, not another String):
Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);
But consider the format string you're using...there are cleaner options available, as others are suggesting.
Look at the number formatting information on MSDN: Standard Numeric Format Strings, or optionally at the custom format strings: Custom Numeric Format Strings.
For custom number formats:
The "," character serves as both a group separator and a number scaling specifier.
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235
There is so much wrong with your code, that's it's hard to describe every detail.
Look at this example:
namespace ConsoleApplication1
{
using System;
public class Program
{
public static void Main()
{
const int Number = 123456789;
var formatted = string.Format("{0:#,###0}", Number);
Console.WriteLine(formatted);
Console.ReadLine();
}
}
}
I am making a simple numeric expression solver using regexes and right now I'm working at splitting polynomials into its terms. So this is what I got so far:
(.*?)([\+-](.*?))+
This doesn't work when negative numbers are involved. Take 3*-2+1 as an example: the terms I get are 3*, -2 and +1, which is obviously wrong.
I thought I could get away with a negative look behind before the sign so that signs preceded by * or / are discarded:
(.*?)((?<![\*/])[\+-](.*?))+
But this doesn't even work with positive numbers
Suggestions?
Hope you didn't spend a lot of time creating your own parser ;)
I use this code to evaluate expressions:
class Program
{
public static double Evaluate(string expression)
{
using (var stringReader = new StringReader("<dummy/>"))
{
var navigator = new XPathDocument(stringReader).CreateNavigator();
expression = Regex.Replace(expression, #"([\+\-\*])", " ${1} "); // add some space
expression = expression.Replace("/", " div ").Replace("%", " mod ");
return (double)navigator.Evaluate(string.Format("number({0})", expression));
}
}
static void Main(string[] args)
{
Console.WriteLine(Evaluate("3*-2+1"));
}
}
Will output: -5
It is based on the XPathNavigator.Evaluate method. The Regex adds some spaces to the input and then division and modulo symbol are replaced.