-1

I am using data annotations for validation and I want to use a RegularExpression Data annotation to check the string has only ASCII characters.

      public class SomeObject
{
    [Required]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    [MaxLength(4000)]       
    [RegularExpression(@"[^\u0000-\u007F]+")]
    public string Text { get; set; }
}

Can you help me fix the regular expression to allow only ASCII characters

asahun
  • 195
  • 3
  • 16
  • im sure that is nothing like how you can do it. ASCII characters would basically be every key on your keyboard plus more.. so i would image this looks to simple to be valid. Im going to follow this, ps what did google say. – Seabizkit Mar 21 '17 at 18:22
  • @dlatikay you beet me by like 3 secs im sure – Seabizkit Mar 21 '17 at 18:25

1 Answers1

2

If you want to test for the full ASCII set:

[RegularExpression(@"^[\x00-\x7F]+$")]
public string Text { get; set; }

And if not for the full ASCII set (this won't pass for characters other than a-z (uppercase too) and 0-9):

[RegularExpression(@"^\w+$")]
public string Text { get; set; }
bl4y.
  • 530
  • 1
  • 3
  • 10
  • Yea, you're right. Since both upper and lowercase should pass the test, **\w** seems a better choice. – bl4y. Mar 21 '17 at 18:28