Form values arrive as text even when the domain expects a number. Normalize harmless whitespace, parse deliberately and report invalid input before constructing a model. The same idea applies to console arguments and HTTP query parameters.
Worked example
Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.
void main() {
final name = ' Asha Verma '.trim();
final rawSeats = '3';
final seats = int.tryParse(rawSeats);
if (seats == null || seats < 1 || seats > 8) {
print('Choose between 1 and 8 seats.');
return;
}
final words = name.split(RegExp(r'\s+'));
print('Hello, ${words.first}. Your booking has $seats seats.');
print('Normalized name: $name');
}Follow the data and control flow
trim returns a new string; it does not change an existing string in place. tryParse returns an int?, making failed conversion part of the type contract. The guard returns early, so the later code can use the validated seat count.
Interpolation inserts expressions into a readable message. The regular expression splits runs of whitespace, but it is only a display convenience here. Store the full name rather than assuming every person’s identity can be reduced to a first/last-name pair. For URLs, use Uri rather than concatenating unescaped user text.
A mistake to avoid
A successful parse does not prove a valid booking: -4 parses as an integer. Validate the range separately. String length counts UTF-16 code units, so a single user-perceived character can occupy more than one unit; use a suitable grapheme-aware library when a UI needs user-perceived character counts.
Practice and verification
Try an empty seat value, three, 0 and 8. Confirm invalid values do not fall back to a silent booking. Add an explicit non-empty name check and show a helpful message without throwing an uncaught exception.