Home > database >  C# Component Model RegularExpression validator rejecting valid regex data
C# Component Model RegularExpression validator rejecting valid regex data

Time:12-03

This REGEX

        [Required]
        [RegularExpression("^[VB]", ErrorMessage = "The barcode must start with B or V")]
        public string Barcode { get; set; }

fails with the following:

        "Barcode": {
            "rawValue": "B6761126229752008155",
            "attemptedValue": "B6761126229752008155",
            "errors": [
                {
                    "exception": null,
                    "errorMessage": "The barcode must start with B or V"
                }
            ],
            "validationState": 1,
            "isContainerNode": false,
            "children": null
        },

even though the values are shown to be correct..... The regex passes in Regex101.com

enter image description here

I'm not sure where to go with this. Any ideas? If I remove the validator the code runs through to my controller with the correct barcode value.

CodePudding user response:

You are only matching the first word not the entire 'barcode'. So you need to add something to match the rest of the 'barcode'.

One form is to add \d at the end. It tells to you to match one or more digits after the 'V' or 'B' that is required.

Full regex could be: "^[VB]\d "

That will match the whole 'barcode' and solve your problem.

CodePudding user response:

You can use

[Required]
[RegularExpression("^[VB].*", ErrorMessage = "The barcode must start with B or V")]
public string Barcode { get; set; }

By adding .*, you allow the whole string to match the regex pattern. Basically, the ^ is redundant in the current context since the pattern used in RegularExpression attribute just had to match the whole string.

  • Related