0
0
Postmantesting~15 mins

Body validation before sending in Postman - Build an Automation Script

Choose your learning style9 modes available
Validate request body before sending POST request
Preconditions (3)
Step 1: Open Postman and create a new POST request to https://api.example.com/users
Step 2: In the Body tab, select raw and JSON format
Step 3: Enter the JSON body with fields: name (string), email (string), age (number)
Step 4: Before sending, validate that name and email are not empty and age is a positive number
Step 5: If validation passes, send the request
Step 6: If validation fails, do not send and show an error message
✅ Expected Result: Request is sent only if the body fields meet validation rules; otherwise, an error message is shown and request is not sent
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Verify 'name' field is a non-empty string
Verify 'email' field is a non-empty string and contains '@'
Verify 'age' field is a positive number
Best Practices:
Use pre-request scripts to validate body before sending
Use pm.expect assertions for validation
Do not send request if validation fails (throw error in pre-request script)
Keep validation logic clear and simple
Automated Solution
Postman
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.

Common Mistakes - 3 Pitfalls
Not parsing the JSON body before validation
Using pm.test assertions in pre-request script
Not stopping the request when validation fails
Bonus Challenge

Now add data-driven testing with 3 different JSON bodies to validate before sending

Show Hint