wasAsked.

How do you validate nested request objects in React and Spring Boot without trusting client-side checks?

Swiggy · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, React, Spring Boot

Community answers

Posted by wasAsked editorial collection

Server-side validation is the source of truth; client-side validation only improves user experience. The challenge is keeping nested rules consistent. Spring Boot — validating nested objects public record CreateOrderRequest( @NotNull @Valid AddressRequest shippingAddress, @NotEmpty @Size(max = 100) List<@Valid OrderLineRequest> lines, @Size(max = 500) String notes) { } public record AddressRequest(@NotBlank String line1, @NotBlank @Pattern(regexp = "\\d{6}") String pincode) { } public record OrderLineRequest(@NotNull Long productId, @Min(1) @Max(50) int quantity) { } @PostMapping("/api/orders") public ResponseEntity<OrderDto> create(@Valid @RequestBody CreateOrderRequest req) { ... } - @Valid on nested fields and container elements cascades validation into nested objects and list items. - Return field errors with property paths ("lines[2].quantity", "shippingAddress.pincode") in a ProblemDetail response from a @RestControllerAdvice handling MethodArgumentNotValidException. - Cross-field and business rules (stock availability, delivery area, maximum order value) are validated in the service layer or with class-level custom constraints. - Limit sizes (list lengths, string lengths, request body size) to prevent abuse, and consider rejecting unknown JSON properties. React — matching rules for fast feedback - Use React Hook Form with a schema library (zod or yup) describing the same nested structure: address fields, line items with useFieldArray. - Show errors on blur and submit; summarise errors at the top for accessibility, with aria-invalid and aria-describedby on inputs. Mapping server errors back to fields - Convert server property paths ("lines[2].quantity") into React Hook Form paths ("lines.2.quantity") and call setError, so server-only rules appear next to the correct input. Keep the user's input intact. Keeping rules in sync - Generate TypeScript types from the OpenAPI spec (springdoc includes Bean Validation constraints such as required, maxLength, pattern and minimum), and optionally generate zod schemas from it (orval can do this). - Keep complex rules server-only and rely on error mapping, rather than duplicating fragile logic. - Share test cases: the same invalid payloads are tested against the API (integration tests) and the frontend schema (unit tests). Never trust the client for prices, discounts, ownership or totals: the server recalculates and authorises everything.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics