التحقق من المدخلات (Validation)
في هذه الصفحة 8 موضوعات
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
نظرة عامة
الموضوعات
- Jakarta Bean Validation
- المُدقّقات المخصصة (Custom validators)
- تنقية المدخلات (Input sanitization)
تعلّم أولًا
2 ساعة تدريب (تقدير)
مخرجات التعلم
- Validate request DTOs with Jakarta Bean Validation annotations and
@Valid. - Write a custom constraint annotation and validator.
- Use validation groups or separate DTOs for create vs update.
- Distinguish input validation (at the edge) from business-rule validation (in the domain).
الدروس
المختبر والتمارين
Lab
JNR-014-LAB1 · Validated product creation
Outcomes: 1–4 · Time: ~2 h
- Add
POST /productswithCreateProductRequest(name, sku, price, optional description). - Add constraints: name not blank and sized, price positive, description size-limited.
- Write
@ValidSkuwith its validator and apply it. - Use a separate
UpdateProductRequestfor update rules. - Keep "SKU must be unique" as a service check, not an annotation.
Acceptance: invalid requests never reach the service (shown by a service call count or log); business rule lives in the service.
Exercises (assessment: 4 exercises)
| ID | Outcome | Task |
|---|---|---|
| JNR-014-EX01 | 1 | Write a CreateCustomerRequest with name, email, age (18+) constraints and @Valid on the controller. |
| JNR-014-EX02 | 2 | Write @ValidCountryCode (two uppercase letters) with a validator. |
| JNR-014-EX03 | 3 | Design CreateProductRequest and UpdateProductRequest so create requires all fields and update allows a partial set; explain the choice versus groups. |
| JNR-014-EX04 | 4 | Classify each rule as input or business: quantity > 0, stock available, email format, coupon not expired. |
أظهر الحلول
- EX01
record CreateCustomerRequest(@NotBlank String name, @Email @NotBlank String email, @Min(18) int age){}andcreate(@Valid @RequestBody ...). - EX02 Annotation with
@Constraint(validatedBy=...); validator:value == null || value.matches("[A-Z]{2}"). - EX03 Separate DTOs are clearer and easier to read than groups; groups work when you must share one type (
@NotNull(groups=Create.class)). - EX04 Input: quantity > 0, email format. Business: stock available, coupon not expired.
- Outcome 1 is also covered by the lab and quiz; all four outcomes are covered by EX01-EX04.
الاختبار
Outcomes: O1 constraints and @Valid · O2 custom constraints · O3 create vs update · O4 input vs business rules.
اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.
الجزء العملي
Four exercises JNR-014-EX01 to EX04 plus the lab. Pass: quiz at least 8/10, all four exercises correct, lab acceptance met.
أخطاء شائعة
Validating only in the frontend; business rules as annotations.
التقييم
4 exercises.
الصلة بالمسار الوظيفي
Input-related vulnerabilities (JNR-041).