Kaf
Kaf

Reputation: 33819

Regular expression validator for an eight digit long number starting with 1

I know I can use [Required], [StringLength] annotations for validating empty string and length requirements but would like to use same regular expression for validating them as well. I haven't tried as I am not very good on regex.

Regular Expression should validate

1.Empty string (should not be allowed)

2.Length of characters (8)

3.Integer

4.Starting number (should be 1)

Here is the code:

 [DisplayName("Account Number:")]
 [RegularExpression("", 
             ErrorMessage = "An eight digit long number starting with 1 required")]
 public string accountNo { get; set; }

Thanks in advance !

Upvotes: 0

Views: 5330

Answers (3)

Romil Kumar Jain
Romil Kumar Jain

Reputation: 20745

Use this regular expression ^1\d{7}$

or

^1[0-9]{7}$

or, in a crunch,

  ^1[0-9][0-9][0-9][0-9][0-9][0-9][0-9]$

Sample code:

using System.Text.RegularExpressions;
 Regex RegexObj = new Regex(@"^1\d{7}$");
 bool  result=   RegexObj.IsMatch("" );

--result has false value

If you don't want to allow empty string then put following attribuite on the field.

[Required(AllowEmptyStrings = false)]

Upvotes: 6

steve v
steve v

Reputation: 3540

Per the documentation on MSDN, an empty string always passes the regular expression validator and you should use a required attribute if you want to make sure they entered something. Alternately, you can derive your own custom data annotation attribute from the regular expression one and handle the empty condition yourself, perhaps.

Upvotes: 3

Mattias Buelens
Mattias Buelens

Reputation: 20159

To make sure an empty string is valid, add a [Required] attribute with AllowEmptyStrings set to true. This prevents null from being assigned, but allows empty strings.

As for the regular expression, Romil's expression should work fine.

[DisplayName("Account Number:")]
[Required(AllowEmptyStrings = true)]
[RegularExpression(@"^1\d{7}$", 
         ErrorMessage = "An eight digit long number starting with 1 required")]
public string accountNo { get; set; }

EDIT If you also want to prevent empty strings from being validated, simply leave out the AllowEmptyStrings settings (as it defaults to false).

[DisplayName("Account Number:")]
[Required]
[RegularExpression(@"^1\d{7}$", 
         ErrorMessage = "An eight digit long number starting with 1 required")]
public string accountNo { get; set; }

Upvotes: 0

Related Questions