R01
R01

Reputation: 331

Regex With Asp.net Mvc StringLength Attribute

I have Asp.net mvc application where on submit form i am using Regex and StringLength Attribute to check string.Scenario is that i allow some kind of codes but their lengths are different. My Class item regex and attribute is here:`

[StringLength(13,ErrorMessage="Allowed 13 or 12 Characters",MinimumLength=12)]      
[RegularExpression("^(01|04|05|06|pt|pT|Pt|PT|fg|fG|Fg|FG)[0-9]*(FR|fr|Fr|fR)?$", ErrorMessage = "Entered Format Is Incorrect")]
public string BarCode { get; set; }

the problem is that barcodes FG,01,04,06 are 12 in length when PT codes length must be 13. ussualy users use PT codes 90%.. sometimes they insert 12 length PT codes and its mistake. can i have 2 regex same time? and can i validate length for particular codes in regex?.i think [StringLength(13,ErrorMessage="Allowed 13 or 12 } atrribute is not what i need here..

Upvotes: 2

Views: 780

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use

^(?:(?:[Ff][gG]|0[146])(?=.{10}$)|(?:05|[pP][Tt])(?=.{11}$))[0-9]*(?:[Ff][rR])?$

See the regex demo.

Explanation:

  • ^ - start of string
  • (?: - start of a non-capturing alternation group
    • (?:[Ff][gG]|0[146]) - either an fg, Fg, fG or FG sequence or 0 followed with 1, 4 or 6
    • (?=.{10}$) - a positive lookahead that requires any 10 more chars immediately to the right of the current location (10 is used because FG or 01 already take 2 chars making 12 in total)
    • | - or
    • (?:05|[pP][Tt]) - 05, pt, Pt, pT or PT
    • (?=.{11}$) - a positive lookahead that requires any 11 more chars immediately to the right of the current location
  • ) - end of the alternation group
  • [0-9]* - 0+ digits
  • (?:[Ff][rR])? - an optional sequence (1 or 0 times), fr, Fr, fR or FR
  • $ - end of string.

Now, adding KLM07489869FR format support (KLM is 3 char long, thus the rest must be 10, so we place the KLM matching part to the alternative with (?=.{10}$)):

^(?:(?:[Ff][gG]|0[146]|[Kk][Ll][Mm])(?=.{10}$)|(?:05|[pP][Tt])(?=.{11}$))[0-9]*(?:[Ff][rR])?$
                       ^^^^^^^^^^^^

Upvotes: 1

Related Questions