Validating ID Number C# - c#

I am working on this method that validates a student Id number. The credentials of the ID number are; the first character has to be 9, the second character has to be a 0, there can not be any letters, and the number must be 9 characters long. The method will return true if the student id is valid. When I go to test the method manually through main it comes out as true, even when I put in a wrong input. In my code, I have the if statements nested, but I originally did not have them nested. What is a better way to validate the input to align with the credentials of the ID number? Would converting the string into an array be more ideal?
public static bool ValidateStudentId(string stdntId)
{
string compare = "123456789";
if (stdntId.StartsWith("8"))
{
if (stdntId.StartsWith("91"))
{
if (Regex.IsMatch(stdntId, #"^[a-zA-Z]+$"))
{
if (stdntId.Length > compare.Length)
{
if (stdntId.Length < compare.Length)
{
return false;
}
}
}
}
}

You can try regular expressions:
public static bool ValidateStudentId(string stdntId) => stdntId != null &&
Regex.IsMatch(stdntId, "^90[0-9]{7}$");
Pattern explained:
^ - anchor - string start
90 - digits 9 and 0
[0-9]{7} - exactly 7 digits (each in [0..9] range)
$ - anchor - string end
So we have 9 digits in total (90 prefix - 2 digits + 7 arbitrary digits), starting from 90

Related

String validations c#

I have a 9 character string I am trying to provide multiple checks on. I want to first check if the first 1 - 7 characters are numbers and then say for example the first 3 characters are numbers how would I check the 5th character for a letter range of G through T.
I am using c# and have tried this so far...
string checkString = "123H56789";
Regex charactorSet = new Regex("[G-T]");
Match matchSetOne = charactorSetOne.Match(checkString, 3);
if (Char.IsNumber(checkString[0]) && Char.IsNumber(checkString[1]) && Char.IsNumber(checkString[2]))
{
if (matchSetOne.Success)
{
Console.WriteLine("3th char is a letter");
}
}
But am not sure if this is the best way to handle the validations.
UPDATE:
The digits can be 0 - 9, but can concatenate from one number to seven. Like this "12345T789" or "1R3456789" etc.
It'a easy with LINQ:
check if the first 1 - 7 characters are numbers :
var condition1 = input.Take(7).All(c => Char.IsDigit(c));
check the 5th character for a letter range of G through T
var condition2 = input.ElementAt(4) >= 'G' && input.ElementAt(4) <= 'T';
As it is, both conditions can't be true at the same time (if the first 7 chars are digits, then the 5th char can't be a letter).

Regex condition in C#

I have state numbers and state letters of vehicles according to States in DB. State numbers can be old and new type.
Example of new types of state number.
273KL01
002UK02
098KZ03
120US04
...
Example of old types of state number.
R575KMM
A887KDN
M784LKA
X647DUA
...
Bold characters indicates specified State.
User will input his car's state number and choose State. I need to validate If state number can be registered in chosen State. If it not possible(wrong user input) I will show him message like "You entered wrong state number or State" .
I have done this with If-Else statement. But I want to know another way with regex.
As I think, here will be two steps of condition.
Check if number is old type(starts with letter), if true get from DB state letter and check with regex statements.
If case 1 is false, I get from DB state digits and check with regex statements.
I have regex statement for the first condition:
^(?i)f - Where state letter is f.
What will be regex statement for my second conditon?
Or can be it done(two steps both) with one regex statements?
As you further explained that you actually do want to match any letter at the beginning, and any two digits at the end of the string, using a regular expression is indeed the shortest way to solve this.
Regex re = new Regex("^[a-z].*[0-9]{2}$", RegexOptions.IgnoreCase);
Console.WriteLine(re.IsMatch("Apple02")); // true
Console.WriteLine(re.IsMatch("Arrow")); // false
Console.WriteLine(re.IsMatch("45Alty12")); // false
Console.WriteLine(re.IsMatch("Basci98")); // true
Otherwise, if your requirement is simple, e.g. just the letter A or a at the beginning, and 12 or 02 at the end, then you can also solve this easily without regular expressions:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
if (s[0] != 'a' && s[0] != 'A')
return false;
return s.EndsWith("02") || s.EndsWith("12");
}
Examples:
Console.WriteLine(Match("Apple02")); // true
Console.WriteLine(Match("Arrow")); // false
Console.WriteLine(Match("45Alty12")); // false
Console.WriteLine(Match("a12")); // true
Console.WriteLine(Match("a")); // false
Console.WriteLine(Match("12")); // false
Of course you can also expand this to fit your more complex requirement. In your case, you could use char.IsLetter and char.IsDigit to make the checks:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
return s.Length > 2 && char.IsLetter(s[0]) &&
char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}
Note that the IsLetter method also accepts letters from non-English alphabets, so you might need to change that. You could alternatively make a comparison like this:
bool Match(string s)
{
if (string.IsNullOrWhiteSpace(s))
return false;
return s.Length > 2 &&
((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z'))
char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}
Here's what you need:
^[Aa].*[01][2]$
With a few explanations:
^ assert position at start of a line
[Aa] match a single character present in the list below
Aa a single character in the list Aa literally
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[01] match a single character present in the list below
01 a single character in the list 01 literally
[2] match a single character present in the list below
2 the literal character 2
$ assert position at end of a line
If you need it to start with any letter :
^[A-Za-z].*[01][2]$
Given your edit:
I would use this regex:
^[A-Z].{6}|.{5}\d{2}$
Which guaranties that the input is:
Of length 7;
Start with a capital letter OR finishes with two digit

How to format a number such that first 6 digits and last 4 digits are not hidden

How to format a number such that first 6 digits and last 4 digits are not hidden
such that 111111111111111 looks like 111111****1111
You can also use LINQ, substituting chars with indexes more than 5 and less than number.Length - 4 with *:
string number = "111111111111111";
string res = new string(number.Select((c, index) => { return (index <= 5 || index >= number.Length - 4) ? c : '*'; }).ToArray());
Console.WriteLine(res); // 111111*****1111
One simple way to do this is to slit the input..
int number = 111111111111111;
string firstsix = number.ToString().Substring(0,6) //gets the first 6 digits
string middlefour = number.ToString().Substring(6,4) //gets the next 4
string rest = number.ToString().Substring(10, number.ToString().Lenght) //gets the rest
string combined = firstsix + "****" +rest;
You need to use \G anchor in-order to do a continuous string match.
string result = Regex.Replace(str, #"(?:^(.{6})|\G).(?=.{4})", "$1*");
DEMO
IDEONE

How to validate using Regex

My Requirement is that
My first two digits in entered number is of the range 00-32..
How can i check this through regex in C#?
I could not Figure it out !!`
Do you really need a regex?
int val;
if (Int32.TryParse("00ABFSSDF".Substring(0, 2), out val))
{
if (val >= 0 && val <= 32)
{
// valid
}
}
Since this is almost certainly a learning exercise, here are some hints:
Your rexex will be an "OR" | of two parts, both validating the first two characters
The first expression part will match if the first character is a digit is 0..2, and the second character is a digit 0..9
The second expression part will match if the first character is digit 3, and the second character is a digit 0..2
To match a range of digits, use [A-B] range, where A is the lower and B is the upper bound for the digits to match (both bounds are inclusive).
Try something like
Regex reg = new Regex(#"^([0-2]?[0-9]|3[0-2])$");
Console.WriteLine(reg.IsMatch("00"));
Console.WriteLine(reg.IsMatch("22"));
Console.WriteLine(reg.IsMatch("33"));
Console.WriteLine(reg.IsMatch("42"));
The [0-2]?[0-9] matches all numbers from zero to 29 and the 3[0-2] matches 30-32.
This will validate number from 0 to 32, and also allows for numbers with leading zero, eg, 08.
You should divide the region as in:
^[012]\d|3[012]
if(Regex.IsMatch("123456789","^([0-2][0-9]|3[0-2])"))
// match

regular expression for 2 string arguments having numeric values with range constraint

I need to validate console input arguments. User can pass only 2 arguments separated by Space.
First argument should be between 1 to 100
Second argument should be between 1 to 750.
I need a regular expression to validate the input. Please help.
Description
this regex will match 1-100 space 1-750
^\b([1-9][0-9]?|100)\b\s+\b([1-9][0-9]?|[1-6][0-9]{2}|7[0-4][0-9]|750)\b$
Expanded
^ match the start of the string
\b match the word boundary
( open capture group 1
[1-9] match any single digit not including zero followed by
[0-9]? match any single digit or no digit
| or
100 match the number one hundred
) close the capture group 1
\b\s+\b require a word break, space, and word break.
( start capture group 2
[1-9] match any single digit not including zero followed by
[0-9]? match any single digit or no digit
| or
[1-6] match any digits 1 thru 6 followed by
[0-9]{2} match two of any digits
| or
7 match a seven followed by
[0-4] match digits 0 thru 4 followed by
[0-9] match any single digit
| or
750 match the number seven hundred and fifty
) close the capture group
\b$ require a word break and end of string.
It sounds like you want a pattern like this:
^(1|[1-9]\d|100)\s+(1|[1-9]\d|[1-6]\d\d|7[0-5]\d)$
However, you are probably better off verifying the inputs via normal integer comparison:
int int1, int2;
if (int.TryParse(param1, out int1) && int.TryParse(param2, out int2))
{
if (int1 >= 1 && int1 <= 100 && int2 >= 1 && int2 <= 750)
{
...
}
}
As others have said, regex isn't the best option, but if you really want to use it, this seems to work...
^(?:100|[1-9]\d?) (?:[1-7](?:[0-4]\d|50)|[1-9]\d?)$
I rather recommend not using regex but something like this:
int a=0,b=0;
if(args.Length != 2){
// not 2 arguments
}else{
if(!int.TryParse(args[0], out a) || !int.TryParse(args[1], out b)){
// not numbers
}else{
if(a < 1 || a > 100 || b < 1 || b > 750){
// out of ranges
}else{
// everything fine
}
}
}
and you'll have your numbers right there.

Categories

Resources