How to check text contain alphabet and digit - asp.net

I have a textbox that user enter a string into it.
<td class ="auto-style2" > <asp:TextBox ID="TextBox_PassportCode" runat="server" Width ="100%"></asp:TextBox></td>
and:
string code=TextBox_PassportCode.text;
I want to check if "code" contain alphabet + digit together. Eg,A1234 or 1234A Or fhg21564,
It is not important how many alphabet or how many digit user enter, but textbox should contain alphabet and digit.

Try doing like below. Since you said the text could be either A1234 or 1234A; it not necessary that string starts with alphabet. In which case, you can check against regular expression [a-zA-Z0-9]+ which will match combination of 1 or more alphabet + digits. See MSDN on how to use
string code=TextBox_PassportCode.text;
string pat = "[a-zA-Z0-9]+";
if (System.Text.RegularExpressions.Regex.IsMatch(code, pat, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
System.Console.WriteLine("Match Found");
}
else
{
System.Console.WriteLine("No Match");
}

Use a regular expression for this.
See this answer.
C# Regex to allow only alpha numeric

Related

regular expression validate textbox at least two words is required

i have a text box and i need validate it with regular expression at least two words in text box, and not contain spaces in the first character. pls give me a regular expression to validate my textbox
Currently I am using
^((\b[a-zA-Z]{2,40}\b)\s*){2,}$
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
controltovalidate="TextBox1" validationexpression="^((\b[a-zA-Z]{2,40}\b)\s*){2,}$"
errormessage="at least two words"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" OnClick="btnClick" runat="server" Text="Button" />
Assuming they can be separated by any whitespace character (space, tab, etc):
^[a-z]+(?:\s[a-z]+)+$
Here's the breakdown:
Assert position at the beginning of the string ^
Match a single character in the range between “a” and “z” [a-z]+
Between one and unlimited times, as many times as possible +
Match the regular expression below (?:\s[a-z]+)+
Between one and unlimited times, as many times as possible +
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) \s
Match a single character in the range between “a” and “z” [a-z]+
Between one and unlimited times, as many times as possible +
Assert position at the end of the string (or before the line break at the end of the string, if any) $
...But if they're separated by only a space:
^[a-z]+(?: [a-z]+)+$
...or if any non-word character for the separator:
^[a-z]+(?:\W[a-z]+)+$
This should be used with RegexOptions.IgnoreCase. For example (in C#):
if (Regex.IsMatch(subjectString, #"^[a-z]+(?:\W[a-z]+)+$", RegexOptions.IgnoreCase)) {
// Successful match
} else {
// Match attempt failed
}
Your are probably looking for this:
^[a-zA-Z]{2,40}(?: +[a-zA-Z]{2,40})+$
Description:
^ # anchor for the start of the string
[a-zA-Z]{2,40} # ascii letters
(?: # open a non-capturing group
[ ]+[a-zA-Z]{2,40} # one or more spaces followed by letters
)+ # repeat the group one or more times
$ # anchor for the end of the string
Note that word boundaries are useless.

Allow only alphanumeric character

i want to allow only alphanumeric password i have written following code to match the same
but the same is not working
Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") never return false
even if i type password test(which do not contain any number).
ElseIf Regex.IsMatch(txtpassword.Text, "^[a-zA-Z0-9_]*$") = False Then
div_msg.Attributes.Add("class", "err-msg")
lblmsg.Text = "password is incorrect"
I have tried this also
Dim r As New Regex("^[a-zA-Z0-9]+$")
Dim bool As Boolean
bool = r.IsMatch(txtpassword.Text) and for txtpassword.Text = '4444' , bool is coming true i dont know what is wrong.
First of all, the '_' is not a valid alpha-numeric character.
See http://en.wikipedia.org/wiki/Alphanumeric
And, second, take another look at your regular expression.
[a-zA-Z0-9_]*
This can match 0 OR more alpha-numeric characters or 0 OR more '_' characters.
Using this pattern, a password '&#&#^$' would return TRUE.
You probably want to test for 1 OR more characters that ARE NOT an alpha-numeric. If that test returns TRUE, then throw the error.
Hope this helps.
Try the following Expression:
([^a-zA-Z0-9]+)
This will match if your Password contains any character that is not alphanumeric.
If you get a match, do your error handling.
So based on the Regex that you have in the question, it appears you want a password with one lower-case and upper-case letter, one number, and an _; so here is a Regex that will do that:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*_).{4,8}
Debuggex Demo
The {4,8} indicates the length of the password; you can set that accordingly.

ASP.net validator regular expression and accented names / characters

I have a asp.net control that is using a regular expression to validate the users input for first name and last name. It works for up to 40 characters...and I think by the looks of the expression it also allows ' for names like O'Donald and maybe hypenated names too.
ValidationExpression="^[a-zA-Z''-'\s]{1,40}$"
My problem is with accented names/characters e.g. Spanish and French names that may contain for example ñ are not allowed. Does anyone know how to modify my expression to take this into account?
You want
\p{L}: any kind of letter from any language.
From regular-expressions.info
\p{L} or \pL is every character in the unicode table that has the property "letter". So it will match every letter from the unicode table.
You can use this within your character class like this
ValidationExpression="^[\p{L}''-'\s]{1,40}$"
Working C# test:
String[] words = { "O'Conner", "Smith", "Müller", "fooñ", "Fooobar12" };
foreach (String s in words) {
Match word = Regex.Match(s, #"
^ # Match the start of the string
[\p{L}''-'\s]{1,40}
$ # Match the end of the string
", RegexOptions.IgnorePatternWhitespace);
if (word.Success) {
Console.WriteLine(s + ": valid");
}
else {
Console.WriteLine(s + ": invalid");
}
}
Console.ReadLine();

Digits Regular Expression Validator

i need a regular expression validation for
numeric digits grouped as X-XXXXX-XXX-X
can any one help?
Regex reg = new Regex("\b[0-9]\-[0-9]{5}\-[0-9]{3}\-[0-9]\b");
Here is what I use for checking social security numbers that user's input:
Public Shared Function CheckSSNFormat(ByVal text As String) As Boolean
Dim digits As String = Regex.Replace(text, "[^0-9]", "")
Return digits.Length = 9
End Function
It doesn't check that they are input in a specific format, but that might be better depending on what you really need -- so just thought I'd give you another option, just incase.
The above just removes everything except digits, and returns true if there are 9 digits (a valid SS#). It does mean some goofy user could enter something like: hello123456789 and it would accept it as valid, but that is fine for me, and I'd rather do that than not accept 123456789 just because I was looking for 123-45-6789 only.
Later I use this to save to my database:
Public Shared Function FormatSSNForSaving(ByVal text As String) As String
If text = "" Then text = "000-00-0000"
Return Regex.Replace(text, "[^0-9]", "")
End Function
and this anytime I want to display the value (actually I use this one for phone numbers, turns out I never display the SS# so don't have a function for it):
Public Shared Function FormatPhoneForDisplay(ByVal text As String) As String
If text.Length <> 10 Then Return text
Return "(" & text.Substring(0, 3) & ") " & text.Substring(3, 3) & "-" & text.Substring(6, 4)
End Function
(^\d{1}-\d{5}-\d{3}-\d{1}$), this should do.
[0-9]-[0-9]{5}-[0-9]{3}-[0-9]
you could also use round brackets to extract the numbers if you want:
([0-9])-([0-9]{5})-([0-9]{3})-([0-9])
and get the values with $1 $2 etc. in the Regex.Replace() function
Regex pattern = new Regex("\b\d-\d{5}-\d{3}-\d\b");
\b - word boundary
\d - digit

What is the regular expression for "No quotes in a string"?

I am trying to write a regular expression that doesn't allow single or double quotes in a string (could be single line or multiline string). Based on my last question, I wrote like this ^(?:(?!"|').)*$, but it is not working. Really appreciate if anybody could help me out here.
Just use a character class that excludes quotes:
^[^'"]*$
(Within the [] character class specifier, the ^ prefix inverts the specification, so [^'"] means any character that isn't a ' or ".)
Just use a regex that matches for quotes, and then negate the match result:
var regex = new Regex("\"|'");
bool noQuotes = !regex.IsMatch("My string without quotes");
Try this:
string myStr = "foo'baa";
bool HasQuotes = myStr.Contains("'") || myStr.Contains("\""); //faster solution , I think.
bool HasQuotes2 = Regex.IsMatch(myStr, "['\"]");
if (!HasQuotes)
{
//not has quotes..
}
This regular expression below, allows alphanumeric and all special characters except quotes(' and "")
#"^[a-zA-Z-0-9~+:;,/#&_#*%$!()\[\] ]*$"
You can use it like
[RegularExpression(#"^[a-zA-Z-0-9~+:;,/#&_#*%$!()**\[\]** ]*$", ErrorMessage = "Should not allow quotes")]
here use escape sequence() for []. Since its not showing in this post

Resources