ValidateRegularExpression not working

Hi Mythz,

I am trying to use the [ValidateRegularExpression} like so:

[ValidateRegularExpression(
    pattern : @"^\+[1-9]\d{1,14}$",
    ErrorCode = "InvalidPhoneNumber", 
    Message = "You must supply phone number in E.164 format")]
public string Number { get; set; }

I have tested the regex here, it matches strings like “+1234567” but not when validating the request, it always comes back as a fail.

I can’t find any usage examples in docs so I am not sure if I am doing it wrong.

Here is full response:

{
    "responseStatus": {
        "errorCode": "InvalidPhoneNumber",
        "message": "You must supply phone number in E.164 format",
        "errors": [
            {
                "errorCode": "InvalidPhoneNumber",
                "fieldName": "Number",
                "message": "You must supply phone number in E.164 format",
                "meta": {
                    "RegularExpression": "^\u002B[1-9]d{1,14}$",
                    "PropertyName": "Number",
                    "PropertyValue": "\u002B1234567"
                }
            }
        ]
    }
}

What did I miss?

It’s because the \ escape char needed to be double escaped since the pattern was embedded as a normal #Script string before being passed to Fluent Validation’s Regular Expression Validator.

I’ve updated it to use #Script Prime Quotes which ignores the escape char so it’ll use the pattern verbatim. This change is available from v8.2.3+ which is now available in Pre Release packages.

1 Like