1

I have different cases:

  1. No spaces allowed at all
  2. 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 ?

Mazen Elkashef
  • 3,430
  • 6
  • 44
  • 72

5 Answers5

3

The \S escape sequence matches anything that isn't a whitespace character.

Thus the regexes that you need follow:

  1. ^\S+$

  2. ^\S.*\S$

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

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
Tejs
  • 40,736
  • 10
  • 68
  • 86
  • "You know the saying about regex's (now you have two problems)" I'm sorry, what =S ? – Mazen Elkashef Apr 15 '11 at 12:17
  • "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." – Tejs Apr 15 '11 at 12:17
  • Ok I understand that RegEx is not an optimum solution and it will bring more problems .. why exactly is what I'm trying to understand now! =) .. btw do you think that the solution for this question is bad too http://stackoverflow.com/questions/5644073/asp-net-rangevalidator-behaving-strangely ? – Mazen Elkashef Apr 15 '11 at 12:23
  • Don't get me wrong; Regex's are a useful tool, particular for very complex problems. However, there is always going to be overhead when running a regex because whatever regex you use, some parser has to parse the expression and figure out what needs to be done compared to just running code you made yourself. – Tejs Apr 15 '11 at 12:25
  • hmm .. Look, I'll use this validation to validate some user information of new users upon registration, and also on a field or two in like 19 pages (each page adds a certain item to my system and it's not used frequently) .. so do you think what's better here ? and if you could read the question I just posted in the last comment cause I wander if you have alternative solutions to the RegEx in such case !? – Mazen Elkashef Apr 15 '11 at 12:31
1

No spaces allowed at all:

^\S+$

No spaces allowed at the beginning or end:

^\S+.*\S+$
Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • The expression: `^\S+.*\S+$` suffers from [Catastrophic Backtracking](http://www.regular-expressions.info/catastrophic.html "Or exponential, super-linear, never-ending") for longish strings that don't end with a `\S`. (Each `\S` character in the string can be matched three different ways!) Also this expression does not match a string containing just one non-space. Instead, I would use: `^\S(.*\S)?$` – ridgerunner Apr 15 '11 at 15:25
1

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.

Community
  • 1
  • 1
Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • Justin Morgan I really appreciate your help .. thanks for the full answer .. just one last question. I've read your answer in the referred question "Perhaps most importantly: If you think about the problem for five minutes, can you come up with an idea of how to solve it with string manipulation?" I think I both problems could be solved in a couple lines of code instead of RegEx but again you say "writing a CustomValidator for a pretty meager performance boost" so RegEx to solve both problems or 2 CustomValidators for the length and the spaces !!? – Mazen Elkashef Apr 15 '11 at 13:47
  • @lKashef - The answer to your question was too long to fit in a comment, so please see my edit. – Justin Morgan - On strike Apr 15 '11 at 15:11
  • @Justin .. Thanks for your time :) and I hope you're right :D – Mazen Elkashef Apr 15 '11 at 16:14
  • @Justin .. When I started to code I realized that I need two seprate validators cause I can't tell the user "The input can't contain spaces or have more than 50 characters". it doesn't make sense! .. so do you still think that RegEx is the best solution here ? and if so what's the RegEx for them separately. I know you're an expert in RegEx so I was hoping that you could consider ridgerunner's comment on Aliostad's answer. – Mazen Elkashef Apr 16 '11 at 01:06
  • @lKashef - Sorry, I didn't notice your answer right away. Basically, in your situation I'd go with whatever you're most comfortable with. Personally, I'd go with two separate regex: `^\S*$` for no spaces and `^.{0,50}$` for length 50 or less. BTW, thanks for calling me a regex expert! I don't know if I'll ever feel like an expert no matter how much I learn. – Justin Morgan - On strike Apr 20 '11 at 19:54
  • @lKashef - One thing I just thought of: If your input control is a TextBox in MultiLine mode, you should allow newline (`\n`) characters as well. To do that, replace the `.` in two of the regexes I gave you with `[\s\S]`. – Justin Morgan - On strike Apr 20 '11 at 19:57
  • @Justin .. No problem at all .. and for me you're an expert :D Wish you a good luck in this thing, It's pretty complex and rich I know. and of course thanks again for the new Regexes. +1 – Mazen Elkashef Apr 21 '11 at 09:07
0

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;
Quick Joe Smith
  • 8,074
  • 3
  • 29
  • 33