I need to add a RegEx validation for email in my Azure API Management Policy expression but there is no proper documentation available.
Is it possible to have RegEx validation in Azure APIM?
I need to add a RegEx validation for email in my Azure API Management Policy expression but there is no proper documentation available.
Is it possible to have RegEx validation in Azure APIM?
This can be done by setting a variable with C# regex code.
The variable can be used in the choose policy for further processing
Complete policy return result of regex match:
<policies>
<inbound>
<base />
<set-variable name="isEMailValid" value="@{
var pattern = @"^((([!#$%&'*+\-/=?^_`{|}~\w])|((?!.*\.\.)[!#$%&'*+\-/=?^_`{|}~\w][!#$%&'*+\-/=?^_`{|}~\.\w]{0,}[!#$%&'*+\-/=?^_`{|}~\w]))[@]\w+([-.]\w+)*\.\w+([-.]\w+)*)$";
var body = (JObject)context.Request.Body.As<JObject>(true);
var regex = new Regex(pattern);
if(regex.Match(body["email"].Value<string>()).Success)
{
return true;
}
return false;
}" />
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
var response = new JObject();
response["isEMailValid"] = context.Variables.GetValueOrDefault<bool>("isEMailValid");
return response.ToString();
}</set-body>
</return-response>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Request valid:
POST https://rfqapiservicey27itmeb4cf7q.azure-api.net/sample/ipsum HTTP/1.1
Host: rfqapiservicey27itmeb4cf7q.azure-api.net
{ "email": "a@b.com"}
Response valid:
HTTP/1.1 200 OK
content-length: 28
content-type: application/json
date: Fri, 03 Feb 2023 07:15:32 GMT
vary: Origin
{ "isEMailValid": true }
Request invalid: