Hello there,
How can i validate a response field having a regex pattern?
Thank you!!
Hello there,
How can i validate a response field having a regex pattern?
Thank you!!
Using the match assertion.
The following is an example from a previous question.
var array = ["123", "ABC", "123ABC"]
// following regex match allows only Alphanumeric
// It doesn't allow 'only alpha' or 'only numbers'.
array.forEach(string =>
pm.test(`${string} is alphanumeric`, () => {
pm.expect(string).to.match(/((^[0-9]+[a-z]+)|(^[a-z]+[0-9]+))+[0-9a-z]+$/i);
})
);
// following regex allows alphanumeric, only alpha, and only numbers.
array.forEach(string =>
pm.test(`${string} is alphanumeric v2`, () => {
pm.expect(string).to.match(/^([0-9]|[a-z])+([0-9a-z]+)$/i);
})
);
Thanks mdjones for the pointer.
I am planning to validate the response schema as a whole instead of applying field level validations.
because of different fields having different regex patterns.
Not sure if schema validation supports the regex pattern? if yes - then my problem is solved
else i may proceed with the additional logic that you supplied.
Thanks,
Itishree
The problem with trying to validate multiple elements in one go, is that when you have failures, its not always easy to work out which element failed.
Hence the advice for tests to be singular.
If you have a pm.test block with multiple pm.expect assertions. The first assertion that fails will be what is reported in the test results tab. It wonβt evaluate the remaining assertions, and you wonβt get feedback on those elements until you fix the initial assertion. You may have multiple bugs and not know it. So the advice would be to test each element separately, and in its own pm.test block.
Postman can validate a schema, that the required elements are being returned etc and the type of data. (number, string, boolean) but it canβt do a regex match at this level as far as Iβm aware.
For exampleβ¦
const schema = {
"type": "object",
"properties": {
"training_details": {"type": "object",
"properties": {
"id": { "type": "string"},
"start_date": { "type": "string"},
"end_date": { "type": "string"},
},
"required": ["id", "start_date","end_date"]
}
},
};
pm.test('API response schema is valid', () => {
pm.expect(response).to.have.jsonSchema(schema);
});