Home > Mobile >  Prevent forms in entering a space and inserting to the database
Prevent forms in entering a space and inserting to the database

Time:02-27

I would like to ask if there is a RegEx to prevent or avoid entering only a space or many space and inserting it to the database. I am using ASP.NET and MVC, in my forms.

The conditions are as follows:

  • "[space][space]" = should not be accepted or inserted in the database
  • "[space]" = should not be accepted or inserted in the database
  • "[space]name = should be accepted or inserted in the database
  • "name[space]of[space]a[space]person" = should be accepted or inserted in the database

What I am trying to prove is that, if I am testing, a space should not be accepted, but If I type a name example "Mary Jane" it will be accepted or even a letter. I even tried \s or \S but still would not work.

Hoping you could help me with this.

CodePudding user response:

You can check string is all of whitespaces(^ - begin of line, $ - end of line), or check exist one not whitespace character

public class Program
{
    static void Main(string[] args)
    {
        var whiteSpaces = "       ";
        var hasValue = "Hello World";
        var emptyRegexp = new Regex("^\\s $");
        
        if (emptyRegexp.IsMatch(whiteSpaces))
        {
            Console.WriteLine($"{nameof(whiteSpaces)} has only space characters");
        }
        
        if (emptyRegexp.IsMatch(hasValue))
        {
            Console.WriteLine($"{nameof(hasValue)} has only space characters");
        }

        var fillRegex = new Regex("\\S");

        if (fillRegex.IsMatch(whiteSpaces))
        {
            Console.WriteLine($"{nameof(whiteSpaces)} has not only space characters");
        }

        if (fillRegex.IsMatch(hasValue))
        {
            Console.WriteLine($"{nameof(hasValue)} has not only space characters");
        }
    }
}

CodePudding user response:

Use the String.Trim method here this will get rid of all leading and trailing spaces.

  • Related