Validate request body before sending POST request
Preconditions (3)
✅ Expected Result: Request is sent only if the body fields meet validation rules; otherwise, an error message is shown and request is not sent
const body = pm.request.body.raw; try { const jsonBody = JSON.parse(body); pm.expect(jsonBody).to.have.property('name').that.is.a('string').and.is.not.empty; pm.expect(jsonBody).to.have.property('email').that.is.a('string').and.is.not.empty; pm.expect(jsonBody.email).to.include('@'); pm.expect(jsonBody).to.have.property('age').that.is.a('number').and.is.above(0); } catch (e) { throw new Error('Request body is not valid JSON or missing required fields'); } // If validation fails, throw error to stop request if (!jsonBody.name || !jsonBody.email || !jsonBody.email.includes('@') || typeof jsonBody.age !== 'number' || jsonBody.age <= 0) { throw new Error('Validation failed: name and email must be non-empty, email must contain @, age must be positive number'); }
This script runs in the Pre-request Script tab in Postman before sending the request.
It parses the raw JSON body and checks that name and email are non-empty strings, email contains '@', and age is a positive number.
If any check fails, it throws an error which stops the request from being sent and shows the error message.
This ensures only valid request bodies are sent, preventing server errors and improving test reliability.
Now add data-driven testing with 3 different JSON bodies to validate before sending
username before sending?const body = JSON.parse(pm.request.body.raw);
pm.expect(body.age).to.be.a('number');
What will happen if the request body is {"age": "twenty"}?email field:
const body = JSON.parse(pm.request.body.raw); pm.expect(body.email).to.not.be.empty;But the test always passes even when
email is missing. What is the likely problem?email exists before checking emptiness -> Option Did or if id is not a positive integer. Which Postman pre-request script correctly validates this before sending?Pass the test and this pattern moves unknown