-2

I have Required attribute for some strings in my view model, but that doesn't catch if user types, say, (yes, whitespace) into the text area. I need to prevent user to submit whitespace-only strings.

I am trying to use RegularExpression attribute on my view model's properties to validate the string. I've seen some answers such as Filtering "whitespace-only" strings in JavaScript or How to validate whitespaces using jquery/ajax in an MVC view but they don't seem to work properly (yes, before you ask, I am omitting leading and trailing /s if I'm taking it from Javscript to C#). The examples at the answers to those questions usually validate only against whitespace, or no whitespace at all. What I need is that I need at least some text to validate. Having some whitespace is no problem as long as I also have some non-whitespace string too.

What regex should I use (I am not good with regexes) in my attribute to validate some text that contains at least some non-whitespace text?

Community
  • 1
  • 1
Can Poyrazoğlu
  • 31,161
  • 42
  • 171
  • 354

4 Answers4

1

The Regex needed is ^(.*\S.*)$. This will allow spaces if there is another "real" character.

In an attribute it would look something like.

//using System.ComponentModel.DataAnnotations;

[Required, RegularExpression(@"^(.*\S.*)$")]
public string Name { get; set; }

I tried adding Required(AllowEmptyStrings = false) first with no success, but that is what Microsoft says to do. It didn't work for me but the Regex above did.

thalacker
  • 1,639
  • 20
  • 33
-1

You can add these data-annotations to your strings:

    [Display(Name = "Email")]
    [Required(ErrorMessage = "Please enter email address !", AllowEmptyStrings = false)]
    public string Email { get; set; }

The part AllowEmptyStrings = false will prevent you from saving empty strings (like a whitespace)

-1

the regular expression ^\s+$ matches strings that consist only of whitespace.

the regular expression \S matches strings that contain some non-whitespace.

neuhaus
  • 3,588
  • 1
  • 9
  • 24
-1

Try this expression: ^\S+$

Tested at http://regexr.com/3cq34.

Sebastian
  • 1,069
  • 3
  • 16
  • 30