16

I'm developing a Login View in MVC5.

I would like to set at the ViewModel level a DataAnnotation to state the the field does NOT accept empty spaces.

Is there a Data Annotation in MVC (something like [NoSpaces] that can be used to NOT allow a string field to contain "spaces" ?

SF Developer
  • 5,244
  • 14
  • 60
  • 106
  • You want the RegularExpression validator. http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.110).aspx I am nut good with regular expressions, but this validator is the one you need. – Nigel Ellis Oct 30 '14 at 16:48
  • OK ...may I ask if you requested to close this question? – SF Developer Oct 30 '14 at 16:52
  • Wasn't me that requested the question be closed. – Nigel Ellis Oct 30 '14 at 16:56

3 Answers3

39

How about this:

[RegularExpression(@"^\S*$", ErrorMessage = "No white space allowed")]
Undo
  • 25,519
  • 37
  • 106
  • 129
Kirby
  • 1,739
  • 1
  • 17
  • 21
1

Well, the simplest but robust thing I can think of is to look at how existing code works, or how existing data annotation work.

For example, let's look at the System.ComponentModel.DataAnnotations.StringLengthAttribute class.

Here's the definition only (just to keep short):

namespace System.ComponentModel.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class StringLengthAttribute : ValidationAttribute
    {
        public StringLengthAttribute(int maximumLength);

        public int MinimumLength { get; set; }

        public override string FormatErrorMessage(string name);
       
        public override bool IsValid(object value);
    }
}

So I would simply copy the original implementation source code from GitHub and customize it to my needs. For example, to obtain a signature like this (if I understood correctly and this is what you wanted):

public StringLengthAttribute(int maximumLength, int minLength = 0, allowEmptySpaces = true);

For more in-depth info, I would also read the Microsoft docs on the ValidationAttribute class, which is your base class for custom validation data annotations.

EDIT:

I would NOT rely on Regular Expressions to validate data in cases where I just need to exclude empty strings or strings containing only white space(s), because Regular Expressions are very expensive to process (and require a lot of memory allocation, because of an expression compiler, a state machine, etc.).

Paul-Sebastian Manole
  • 2,538
  • 1
  • 32
  • 33
0

If this is convenient for anyone, I got pass this issue by doing this on the client:

//trim each form input

var $form = $("#myForm");
$form.find("input:text").each(function(){
   var $self= $(this);
   $self.va($self.val().trim());
});

//then validate before submit

if($form.valid()){ $form.submit(); }

// on the server ModelState.Isvalid does verify each item with [Required] and won't accept only white spaces from an input (but this means additional roundtrip to server and it's not always convenient)

sTx
  • 1,213
  • 13
  • 32
  • This is not a good practice to do it at the client side. It will work fine as long as you control the client, but if someone would send e request in a different way, your server won't even handle this scenario. Server should implement that check ALWAYS.. – infografnet Nov 19 '20 at 11:14