Is there a way to validate 'live' input field using Regex in C#?
'live' means that I don't validate complete string, I want to validate the string while it's typed.
For example, I want my string to match the next pattern lalala111#alalala123, so I have to check each new char - is it # ? if it's # then is there a # already in the string? if yes, then I return a null, if no, then I return the char. And of course I have to check chars - is it letter or digit? if yes, then ok, if not, then not ok.
I hope you got my idea.
At now I have this code
private char ValidateEmail(string input, int charIndex, char charToValidate)
{
if (char.IsLetterOrDigit(charToValidate) &&
!(charToValidate >= 'а' && charToValidate <='я') &&
!(charToValidate >= 'А' && charToValidate <= 'Я') ||
charToValidate =='#' ||
"!#$%&'*+-/=?^_`{|}~#.".Contains(charToValidate.ToString()))
{
if ((charToValidate == '#' && input.Contains("#")) ||
(!input.Contains("#") && charIndex>=63) ||
(input.Contains("#") && charIndex >= 192))
return '\0';
}
else
{
return '\0';
}
return char.ToUpper(charToValidate);
}
it allows only latin letters with digits and some special characters, and also it allows first part of the string (before #) to have only 64 letters, and the second part (after #) to have only 128 letters, but the code looks ugly, don't it? So I want to do all these checks in one beauty regular expression.
lYou have to use the following code:
Declare this line at top:
System.Text.RegularExpressions.Regex remail = new System.Text.RegularExpressions.Regex(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
next either on button click or leave event pass the following code to check
if (textemail.Text != "" && !remail.IsMatch(textemail.Text))
{
errorProvider1.Clear();
textemail.Focus();
errorProvider1.SetError(textemail, "Wrong Email ID");
MessageBox.Show("Wrong Email ID");
textemail.SelectAll();
return;
}
After a character has been typed, you want the string that has been entered to match one of the following:
between 1 and 64 (inclusive) acceptablecharacters.
between 1 and 64 (inclusive) acceptable characters then an # character.
between 1 and 64 (inclusive) acceptable characters then an # character then 128 or fewer acceptable characters.
Note that the last two clauses can be combined to say:
between 1 and 64 (inclusive) acceptable characters then an # character then between 0 and 128 inclusive acceptable characters.
Hence the entire requirement can be expressed as:
between 1 and 64 (inclusive) acceptable characters, optionally followed by an # character then between 0 and 128 inclusive acceptable characters.
Where the definition of "acceptable characters" is not at all clear from the question. The code within ValidateEmail does range checks of 'a' to 'я' and of 'А' to 'Я'. It also checks "!#$%&'*+-/=?^_{|}~#.".Contains(...)`.
The text below assumes acceptable characters actually means the 26 letters, upper and lower case, plus the 10 digits.
The required regular expression is then ^\w{1,64}(#\w{0,128})?$
This regular expression can then be used to check the concatenation of the already validated input text plus the character just typed.
If additional characters are wanted to be considered as acceptable then change the \w, there are two of them. For example if underscores (_) and hyphens (-) are to be allowed then change both \ws to be [\w_-].
Related
I'm writing a program for Uni which requires some basic validation.
I have a textbox which allows the user to input their age. I have successfully written a Regex expression which checks if the value entered into the textbox contains numeric values only and is two characters long:
Regex agePattern = new Regex(#"^[0-9]{1,2}\z$"); // Age entered must be numeric characters only (0-9) and may only be two charaters long
if (agePattern.IsMatch(ageBox.Text) == false)
{
MessageBox.Show("Customer's age is not valid. Age must be in numeric format & can only be two characters long"); // If Regex pattern & entered string DO NOT match - user get's this message
return;
}
else
{
// do something
}
My question is, can I extend my Regex expression to constrain age values between 1 and 99?
I've not written any Regex before and I'm struggling.
Thanks!
How about parsing an integer instead?
bool IsValidAge(string ageString) {
int age;
return int.TryParse(ageString, out age) && age >= 1 && age <= 99;
}
Try this regex:
^[1-9]?[0-9]?\z
Or skip regex, parse the text as int and write a function which decide input is between 1 and 99.
Try this regex:
^[1-9]?[0-9]?\z
This matches an empty input (since both digits are optional) as well as 0. Fewer ? are better:
^[1-9][0-9]?$
Try it with A Better .NET Regular Expression Tester (most other online testers don't allow to specify an empty source).
I'm having a hard time on a regex expression.
It's only requirement is that if there is a dot (.) in the word, there must be a letter on either side of the dot. There can be any number of dots in the word and any number of letters in between the dots. There just has to be a letter on either side of a dot.
I have the mostly figured it out but I am having issue with dots that are only separated by one letter (see example below)
Currently I have this expression:
^(\s*[0-9A-Za-z]{1,}[.]{0,1}[0-9A-Za-z]{1,}\s*)+$
this works for the following:
dot.InWord
Multiple.dots.In.Word
d.ot.s
t.wo.Le.tt.er.sB.et.we.en.do.ts
However, this does not work for words if the dots are only seperated by one letter, as follows:
d.o.t.s.O.n.l.y.S.e.p.e.r.a.t.e.d.B.y.O.n.e.L.e.t.t.e.r
Anyone know how I could solve this?
EDIT:
BHustus solution below is the better solution.
However, I did take what BHustus has shown and combined it with what I had before to come up with a less "confusing" pattern just in case anyone else was interested.
^(\s*[\d\w]+([.]?[\d\w]+)+\s*)+$
The key was to have the . and the 1 word after be in its own group and repeat. ([.]?[\d\w]+)+
Thanks.
([\w]+\.)+[\w]+(?=[\s]|$)
To explain:
The first group, in the parentheses, matches 1 or more letter or number (\w is shorthand for [A-Za-z0-9] and + means "match the preceding one or more times", shorthand for {1,}), followed by one period. After it has matched one or more cycles of [\w]+\., the final [\w]+ ensures that there is at least one letter at the end and consumes all characters until it reaches a non-character. finally, the (?=[\s]|$) is a lookahead assertion that ensures there is either whitespace immediately ahead ([\s]), or the end of the string ($) (with | being the regex "OR" character). If the lookahead fails, it doesn't match.
Online demo, showing all your test cases
Do you have to use a Regex? The accepted answer's Regex is pretty difficult to read. How about a simple loop?
for(int i = 0; i < str.length; i++)
{
char ch = str[i];
if(ch == '.')
{
if(i == 0) return false; //no dots at start of string
if(i == str.length - 1) return false; //no dots at end of string
if(str[i + 1] == '.') return false; //no consecutive dots
}
else if(!IsLetter(ch) && !IsNumber(ch))
{
return false; //allow only letters and numbers
}
}
return true;
I'm looking for create RegEx pattern
8 characters [a-zA_Z]
must contains only one digit in any place of string
I created this pattern:
^(?=.*[0-9].*[0-9])[0-9a-zA-Z]{8}$
This pattern works fine but i want only one digit allowed. Example:
aaaaaaa6 match
aaa7aaaa match
aaa88aaa don't match
aaa884aa don't match
aaawwaaa don't match
You could instead use:
^(?=[0-9a-zA-Z]{8})[^\d]*\d[^\d]*$
The first part would assert that the match contains 8 alphabets or digits. Once this is ensured, the second part ensures that there is only one digit in the match.
EDIT: Explanation:
The anchors ^ and $ denote the start and end of string.
(?=[0-9a-zA-Z]{8}) asserts that the match contains 8 alphabets or digits.
[^\d]*\d[^\d]* would imply that there is only one digit character and remaining non-digit characters. Since we had already asserted that the input contains digits or alphabets, the non-digit characters here are alphabets.
If you want a non regex solution, I wrote this for a small project :
public static bool ContainsOneDigit(string s)
{
if (String.IsNullOrWhiteSpace(s) || s.Length != 8)
return false;
int nb = 0;
foreach (char c in s)
{
if (!Char.IsLetterOrDigit(c))
return false;
if (c >= '0' && c <= '9') // just thought, I could use Char.IsDigit() here ...
nb++;
}
return nb == 1;
}
I'm using the following code to accept user input. I want to limit user input to a single alpha (a-z) character only. I'm finding a lot of validations using IsNumber to validate integer input, and a lot of information about using a regex on an input String, but I've been unable to uncover how I would be able to restrict input possibilities with this code. Can someone point me in the right direction?
public char promptForGuess()
{
Console.Write("\nGuess a letter: ");
String pre = Console.ReadKey().Key.ToString();
string pre2 = pre.ToUpper();
char pre3 = Convert.ToChar(pre2);
}
You cannot limit the user only put in a-z chars on the console - you have to check the input, he can write in any character (just think about when the input is redirected to your program from a file with <, e.g. yourapp.exe < input.dat ).
But its easy to check a character is lowercase a-z letter. E.g. with plain, ASCII, C tactic (I will use your defined variables):
if('A' <= pre3 && pre3 <'Z') { // pre3 was made upper in your code
// input OK
} else {
// input NOK
}
With regex:
Regex r = new Regex(#"^[a-zA-Z]$");
return r.IsMatch(pre);
If you cannot allow case-insensitive characters, just change the code I wrote.
Anyway, I think you need Console.Read() (ReadKey also read keys like arrows, F1-F12 etc..., so ALL keys, even tab and caps lock). Refer to MSDN: http://msdn.microsoft.com/en-us/library/system.console.read.aspx
And maybe you should use this function, if you would support unicode letters: http://msdn.microsoft.com/en-us/library/yyxz6h5w.aspx
Note that unicode letters are usually not one bytes! But char can store it. These letters are for example beautiful Hungarian letters with acutes and these king of things: á, é, ő, ű, ö, ü etc (but also French have a lot, and also Dutch etc...)
For judging a valid string, you could judge by
str.length() == 1 && str[0] >= 'a' && str[1] <= 'z'
and for restricting input possibilities, you could write a loop that loops if the input is invalid.
pre = read();
while (!valid(pre))
pre = read();
why don't you use Regex
if (Regex.IsMatch(pre[0].ToString(), #"[A-Za-z]"))
{
//do someting
}
else
{
//do someting
}
I've got a string that I need to verify for validity, the later being so if:
It is completely empty
Or contains a comma-separated string that MUST look like this: 'abc,def,ghi,jkl'.
It doesn't matter how many of these comma separated values are there, but if the string is not empty, it must adhere to the comma (and only comma) separated format with no white-spaces around them and each value may only contain ascii a-z/A-z.. no special characters or anything.
How would I verify whether strings adhere to the rules, or not?
You can use this regex
^([a-zA-Z]+(,[a-zA-Z]+)*)?$
or
^(?!,)(,?[a-zA-Z])*$
^ is start of string
[a-zA-Z] is a character class that matches a single uppercase or lowercase alphabet
+ is a quantifier which matches preceding character or group 1 to many times
* is a quantifier which matches preceding character or group 0 to many times
? is a quantifier which matches preceding character or group 0 or 1 time
$ is end of string
Consider not using regex:
bool isOK = str == "" || str.Split(',').All(part => part != "" && part.All(c=> (c>= 'a' && c<='z') || (c>= 'A' && c<='Z')));