Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC DataAnnotation Accept No Spaces

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" ?

like image 563
SF Developer Avatar asked Oct 30 '14 16:10

SF Developer


2 Answers

How about this:

[RegularExpression(@"^\S*$", ErrorMessage = "No white space allowed")]
like image 182
Kirby Avatar answered Sep 19 '22 07:09

Kirby


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.).

like image 26
Paul-Sebastian Manole Avatar answered Sep 20 '22 07:09

Paul-Sebastian Manole