You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: user_guide.adoc
+41Lines changed: 41 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -310,6 +310,47 @@ definitely not recommended in real-life specs):
310
310
NOTE: There's no need to specify `type` or `size` for fixed contents
311
311
data — it all comes naturally from the `contents`.
312
312
313
+
[[valid-values]]
314
+
=== Validating attribute values
315
+
316
+
To ensure attributes in your data structures adhere to expected formats and ranges, Kaitai Struct provides a mechanism for validating attribute values using the `valid` key. This key allows you to define constraints for values, enhancing the robustness of your specifications. Here's how you can enforce these constraints:
317
+
318
+
* `eq` (or directly `valid: value`): Ensures the attribute value exactly matches the given value.
319
+
* `min`: Specifies the minimum valid value for the attribute.
320
+
* `max`: Specifies the maximum valid value for the attribute.
321
+
* `any-of`: Defines a list of acceptable values, one of which the attribute must match.
322
+
* `expr`: An expression that evaluates to true for the attribute to be considered valid.
323
+
324
+
For most cases, the direct `valid: value` shortcut is preferred for its simplicity, effectively functioning as `valid/eq`.
325
+
326
+
[source,yaml]
327
+
----
328
+
seq:
329
+
- id: exact_value
330
+
type: u1
331
+
valid: 0x42 # Shortcut for eq: The only valid value is 0x42
332
+
333
+
- id: bounded_value
334
+
type: u2
335
+
valid:
336
+
min: 100 # Value must be at least 100
337
+
max: 200 # and at most 200
338
+
339
+
- id: enum_value
340
+
type: u4
341
+
valid:
342
+
any-of: [3, 5, 7] # Value must be one of 3, 5, or 7
343
+
344
+
- id: calculated_value
345
+
type: u4
346
+
valid:
347
+
expr: _ % 2 == 0 # Value must be even
348
+
----
349
+
350
+
When a value does not meet the specified criteria, Kaitai Struct raises a validation error, halting further parsing. This preemptive measure ensures the data being parsed is within the expected domain, providing a first layer of error handling.
351
+
352
+
NOTE: The actual implementation of validation checks is language-dependent and may vary in behavior and supported features across different target languages.
0 commit comments