Regex to limit string length for strings with new line characters - asp.net

Looks like a simple task - get a regex that tests a string for particular length:
^.{1,500}$
But if a string has "\r\n" than the above match always fails!
How should the correct regex look like to accept new line characters as part of the string?
I have a <asp:TextBox TextMode="Multiline"> and use a RegularExpressionValidator to check the length of what user types in.
Thank you,
Andrey

You could use the RegexOptions.Singleline option when validating input. This treats the input as a single line statement, and parses it as such.
Otherwise you could give the following expression a try:
^(.|\s){1,500}$
This should work in multiline inputs.

Can you strip the line breaks before checking the length of the string? That'd be easy to do when validating server-side. (In .net you could use a custom validator for that)
From a UX perspective, though, I'd implement a client-side 'character counter' as well. There's plenty to be found. jQuery has a few options. Then you can implement the custom validator to only run server-side, and then use the character counter as your client-side validation. Much nicer for the user to see how many characters they have left WHILE they are typing.

The inability to set the RegexOptions is screwing you up here. Since this is in a RegularExpressionValidator, you could try setting the options in the regular expression itself.
I think this should work:
(?s)^.{1,500}$
The (?s) part turns on the Singleline option which will allow the dot to match every character including line feeds. For what it's worth, the article here also lists the other RegexOptions and the notation needed to set them as an inline statement.

Related

ASP.NET default regular expression for users' passwords

What is the default regular expression used by asp.net create user wizard?
According to the MSDN documentation, it should be something like this:
Regular Expression: #\"(?:.{7,})(?=(.*\d){1,})(?=(.*\W){1,})
Validation Message: Your password must be 7 characters long, and contain at least one number and one special character.
However, it does not work as it does not accept something like 3edc£edc, which is actually accepted when using the default create user wizard.
Any idea about how can I get this regular expression?
The error is in the ?: in (?:.{7,})(?=(.*\d){1,})(?=(.*\W){1,}) that is "consuming" the fist seven characters or more characters. It should be ?= OR you can invert the order: (?=(.*\d){1,})(?=(.*\W){1,})(?:.{7,})
Just change the order
^(?=(.*\d))(?=(.*\W)).{7,}
I additionally removed the {1,} and anchored it to the start of the string and you don't need a group around the last part
See it here on Regexr

What's the best way to constraint validation to not allow any spaces in ASP.NET

I have different cases:
No spaces allowed at all
No spaces allowed at the beginning or the end of the string only
..A little question, is it good to check (to validate) the input for spaces through the RegEx of the RegularExpressionValidator ?
The \S escape sequence matches anything that isn't a whitespace character.
Thus the regexes that you need follow:
^\S+$
^\S.*\S$
In your previous question, you mentioned you wanted from 0 to 50 characters. If that's still the case, here's what you want:
/^\S{0,50}$/
/^(?!\s).{0,50}(?<!\s)$/
As of right now, I think these are the only regexes posted that allow for less than one letter with the first pattern, and less than two letters with the second pattern.
Regexes are not a "bad" thing, they're just a specialized tool that isn't suited for every task. If you're trying to validate input in ASP.NET, I would definitely use a RegularExpressionValidator for this particular pattern, because otherwise you'll have to waste your time writing a CustomValidator for a pretty meager performance boost. See my answer to this other question for a little guidance on when and when not to use regex.
In this case, the reason I'd use a regex validator has less to do with the pattern itself and more to do with ASP.NET. A RegularExpressionValidator can just be dragged and dropped into your ASPX code, and all you'd have to write would be 10-21 characters of regex. With a CustomValidator, you'd have to write custom validation functions, both in the codebehind and the JavaScript. You might squeeze a little more performance out of it, but think about when validation comes into play: only once per postback. The performance difference is going to be less than a millisecond. It's simply not worth your time as a developer -- to you or your employer. Remember: Hardware is cheap, programmers are expensive, and premature optimization is the root of all evil.
You know the saying about regex's (now you have two problems) - this is doable without regex and should be more performant and easier to read.
string checkString = /* whatever */
if(checkString.IndexOf(" ") > -1)
// Failed Condition 1
if(checkString.Trim() != checkString)
// Failed Condition 2
No spaces allowed at all:
^\S+$
No spaces allowed at the beginning or end:
^\S+.*\S+$
The System.String class contains everything you need:
No spaces allowed at all
This will handle the case of spaces only:
bool valid = !str.Contains(" ");
If you need to check for tabs as well:
char[] naughty = " \t".ToCharArray();
bool fail = (str.IndexOfAny(naughty) == -1);
There are other whitespace characters you could check for, see Character Escapes for more details.
No spaces allowed at the beginning or the end of the string only
A bit simpler, since Trim() will remove any kind of whitespace, including newlines:
bool valid = str.Length == str.Trim().Length;

Regular Expression for percents (with % sign) in ASP.Net RegEx Validator

I need a regex for the ASP.Net (4) Regex Validation control. It needs to be a RegEx validator to support other dynamic behaviors outside the scope of this post..
I was using the following, but it fails if the user enters the % sign following the number (which is a req of my spec):
^(100(?:\.0{1,2})?|0*?\.\d{1,2}|\d{1,2}(?:\.\d{1,2})?)$
I tried adding an atomic group of ^(?>%?) at the end, with no luck, after reading the excellent post
Regular expression greedy match not working as expected
Does anyone have any ideas?
Try this
^(100(?:.0{1,2})?%?|0*?.\d{1,2}%?|\d{1,2}(?:.\d{1,2})?%?)$
try this one instead:
^0*(100(\.00?)?|[0-9]?[0-9](\.[0-9][0-9]?)?)%?$

Validation for TextBox For a User Form

In my User Registration Form, I want my user address text box to accpet alphanumeric as well as special character but should not contain only numeric or special character.
I am currently using regular expression validator ,what regular expression i can use.
Or Is there any different solution for that.
Regards
Here you go.. I have used it at one place, and works pretty well.. just provide your acceptable characters and you are good to go
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/FilteredTextBox/FilteredTextBox.aspx
You mean from your question that a string of alphabets is a must right ?

Help with a regular expression to validate a series of n email addresses seperated by semicolons

I'm using an asp.net Web Forms RegularExpressionValidator Control to validate a text field to ensure it contains a series of email addresses separated by semicolons.
What is the proper regex for this task?
I think this one will work:
^([A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}(;|$))+
Breakdown:
[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4} : valid email (from http://www.regular-expressions.info/)
(;|$) : either semicolon or end of string
(...)+ : repeat all one or more times
Make sure you are using case-insensitive matching. Also, this pattern does not allow whitespace between emails or at the start or end of the string.
The 'proper' (aka RFC2822) regex is too complicated. Try something like (\S+#[a-zA-Z0-9-.]+(\s*;\s*|\s*\Z))+
Not perfect but should be there 90% (haven't tried it, so it might need some alteration)
Note: Not too sure about \Z it might be a Perl only thing. Try $ as well if it doesn't work.

Resources