Search code examples
c#nsregularexpression

Two or more words in regular expression


I have a problem with a regular expression in the next variable

[Required]
       [RegularExpression(@"[a-zA-ZÀ-ÿ\u00f1\u00d1]+",         
ErrorMessage = "No numbers please")]
        [Display(Name = "Name")]
        public string name{ get; set; }

The problem is that in the html form it only accepts one word. I need the input to accept any number of words

I tried using the "+" plus the same regular expression but it doesn't work.

[Required]
        [RegularExpression(@"[a-zA-ZÀ-ÿ\u00f1\u00d1] + [a-zA-ZÀ-ÿ\u00f1\u00d1]",
         ErrorMessage = "No numbers pleas")]
        [Display(Name = "Name")]
        public string name{ get; set; }

And also, the next code

[Required]
        [RegularExpression(@"^[a-zA-ZÀ-ÿ\u00f1\u00d1] +",
         ErrorMessage = "No numbers pleas")]
        [Display(Name = "Name")]
        public string name{ get; set; }

But when I try to put "John Smith" it doesn't work. Could someone explain to me how to fix it


Solution

  • You are missing the blank space inside the brackets and you have an unwanted blank space before the '+' sign. You can try any of the next expressions

    [RegularExpression(@"[a-zA-ZÀ-ÿ\u00f1\u00d1 ]+")]
    

    Or simply

    [RegularExpression(@"[\w ]+")] //Don't forget the white space
    

    \w matches any word character.

    You can also add \s which matches any invisible character. But the space should do the trick.