Chapter 6. Text and Numeric Inputs
This chapter adds a second module, Snippet. It assembles a title, a body, a short config snippet, plus a mark color, reminder time, summary length, priority, contact email, and share password into one card. Each of the six input components is used once. Figure 6-1 shows the key parameters of each of these six components.
Figure 6-1 The six components, each with only a few key parameters listed
This chapter doesn’t list every parameter one by one. For each component it covers only the ones that make a difference. Change one value and what the UI shows or what gets echoed back changes visibly. You can look up the remaining parameters in the component documentation.
The Snippet module looks like this when it first opens.
Figure 6-2 The Snippet module, six kinds of input, nine cells in total
Fill them in and click “Generate”: a card appears on the right, and the cell below writes the received values out verbatim.
Figure 6-3 After generating, one card, plus eight lines of echoed values
6.1 Textbox: type, Line Count, and Length Limits
Textbox comes in three kinds: plain text, password, and email. The type parameter decides which.
var mail = gr.Textbox(label: "Recipient email", type: "email", placeholder: "someone@example.com", interactive: true);
var pass = gr.Textbox(label: "Share password", type: "password", placeholder: "Leave blank for no password", interactive: true);
The one with no type (“Title” in the sample) is the default, text.
type: "text" is the default; it renders as a textarea, even if it is only one line tall. You can see this in the browser. A plain text box and a password box look alike, but the former is a <textarea> and the latter an <input type="password">. So lines only means something for plain text boxes. Password and email boxes are single-line inputs with no height to adjust. All three recognize maxLength. Set maxLength: 5 on a password box, paste 10 characters in, and only 5 remain.
type only changes how the box looks while you type; it doesn’t change the submitted value. All three type values pass a string to the handler function. A password box shows the characters as dots, but submits the plaintext. In Figure 6-3, the “Received values” section reads “Password. hunter2”, which matches the seven dots you see in the input box. A password box is not encryption; it only hides the display. To actually store a password, you have to hash it on the server, and that belongs to Chapter 20.
type: "email" exists for typing convenience. On mobile and desktop browsers the soft keyboard switches to a layout with @ and ., and the input method stops guessing. It does no validation. You can still type abc, and after you click the button it is still submitted exactly as typed. Browsers do check the format of type="email", but only for native form submission, and Gradio’s submission doesn’t go down that path. Treat it as “convenience while typing”, not as “validation”.
Single-Line or Multi-Line
Whether a Textbox is single-line or multi-line is decided by lines, but the behavior is decided by the element the browser gives it. One line tall is <textarea rows="1">, six lines tall is <textarea rows="6">. Both are textareas; the only difference is height. The real dividing line is elsewhere. In a multi-line box, Enter is a newline and does not trigger Submit (Chapter 5). So “should this cell accept multiple lines” decides two things: which height to use, and whether Enter submits.
For one-value-per-cell fields like titles, names, and emails, use the default single line. For things that may have several paragraphs, like body text, descriptions, and logs, give lines a value greater than 1. Don’t set lines: 4 on a single-line box just to “make it look taller”. It becomes a multi-line box, Enter no longer submits, and the user presses Enter thinking nothing happened.
In the sample, all three textboxes are given a value. The title is “Line Wrapping Rules”, the body is two sentences of explanation, and the password and email are left blank. The point of value is “there’s something to click as soon as the page opens”, so the user can try it once without first working out what to fill in. The other two are left blank because there is no sensible default. Giving a password or an email would instead look as though they had already been filled in.
value is used only once, when the page opens. After the user edits the box, it follows the user’s input, and only returns to value when you refresh the page. To “restore the box to its default when a button is clicked”, you have to return that default value from the handler function (the three ways to return, in Chapter 3).
lines and maxLines are a pair. lines is the initial height; maxLines is the upper bound for automatic growth.
var body = gr.Textbox(label: "Body", lines: 4, maxLines: 8, value: SampleNote, interactive: true);
This box opens 4 lines tall. Paste 12 lines in and it grows on its own, stops at 8 lines, and the rest becomes scrolling. In the developer tools you can read two heights: 98 pixels before filling, 177 pixels after pasting 12 lines. That’s about 8 lines. Give lines without maxLines and it keeps growing until it pushes the content below off the screen. Give it an upper bound and it stops there.
maxLength is a hard truncation, and it happens in the browser.
var title = gr.Textbox(label: "Title", value: "Line Wrapping Rules", maxLength: 20, placeholder: "Up to 20 characters", interactive: true);
Paste 30 characters into this box and only the first 20 remain; the extra characters never get in at all. The handler function receives the truncated 20 characters and doesn’t need to cut them again. This is not the same as “the type can’t hold it” from Chapter 3. That one is a runtime error; this one stops the overflow at the input stage.
placeholder is the gray text in an empty box, not a value. When the box has no content it shows “Up to 20 characters”, and it disappears as soon as you start typing; it comes back after you clear the box, but clearing submits an empty string, not that hint. Using value as a hint is a common mistake. The hint then gets submitted as real content.
placeholder and label do different jobs, and you should write both. label says “what this cell is” and stays above the box the whole time; placeholder says “what to fill in” and is gone the moment typing starts. Write placeholder without label and, once the user has typed something, they can no longer tell what the cell is for. This is worst on a long form, when they look back over it.
How the Password Box Actually Behaves
type: "password" is a real password input in the browser, which brings two side effects. First, the browser’s password manager recognizes it. As soon as the page opens it may pop up a “save password” prompt, or autofill the password saved last time. Second, its value doesn’t take part in spell checking and doesn’t support auto-capitalization, so a typo gets no wavy underline.
What gets submitted is plaintext. The “Received values” section in Figure 6-3 is the evidence. The input box shows seven dots, and the handler function gets hunter2. So a password box can stop the person next to you from seeing it, but not the program. This value should never appear in logs, run logs, or exported files. The “Received values” section in the sample is only there so you can see it really is plaintext; in a real application you’d remove that line.
There is one more parameter to cover, submitBtn.
// Illustration: this field is not in the sample
sub = gr.Textbox(label: "Box with a button", placeholder: "Press Enter or click the button on the right", submitBtn: true, interactive: true);
Give it true and a small button appears on the right inside the box; clicking it is the same as pressing Enter in that box. It fires the Submit event (Chapter 5). It suits single-line boxes. The user fills in one line and doesn’t have to move their hand down to a button below.
6.2 Number: Precision and Value Range
Number passes a double to the handler function, but three parameters change that value: precision, minimum, and maximum.
var priority = gr.Number(label: "Priority", value: 2, minimum: 1, maximum: 5, step: 1, precision: 0, interactive: true);
precision: 0 means no decimals. Change precision to 2, type 2.567, and the handler function gets 2.57. It’s rounded to two places before submission. The value itself is changed, not just its display format.
Watch the type too: Number always passes a double, even if you only want integers. precision: 0 merely erases the decimal places; the value is still the double 2.0, not an int. To use an int in the handler function, declare the parameter as int and the framework converts it once according to the declaration (Chapter 3); if you don’t want the conversion, round it yourself inside the function.
minimum and maximum mark out the acceptable range. A value outside the range isn’t clamped to the boundary; instead the whole event fails. Figure 6-4 is the result of entering 9 for Priority (upper bound 5) and clicking Generate.
Figure 6-4 An out-of-range number, the input box turns red, the event fails
The input box turns red first. That’s the browser’s built-in validation; <input type="number" min="1" max="5"> does this by nature. After you click Generate, a red “Error” appears above each of the two output positions. The value failed validation, so the handler function didn’t run to completion.
Notice that the content in those two positions hasn’t changed. The card still reads “Not generated yet.”, and the echo box is still empty. The error is a mark added on top of the existing content, not a replacement. So when you see “Error”, don’t assume the line below was computed this time; it may be left over from the previous run.
This rule runs against many people’s intuition. Most UIs clamp an out-of-range value to the boundary or pop up a hint; here nothing is clamped and it just fails. So when you use Number, set minimum and maximum for values that “really must not be exceeded”, not for values that are “roughly in this range”. If you want a loose range, don’t set them at all and judge in your business logic.
step doesn’t take part in validation. It only affects the increment of the input box’s up/down arrows and where the slider track can stop. Set step to 0.5 and type 7.3: the browser considers the value invalid (stepMismatch), but the value is still submitted and the handler function gets 7.3. To block values like this, you have to check them yourself in the handler function.
What the Number Box Looks Like in the Browser
Number renders as <input type="number">, and the browser gives it a set of built-in behaviors. On the right are two small up/down arrows; one click adds one step. After focusing, the arrow keys also add and subtract. Some browsers even let the scroll wheel change the value. These behaviors are tied to step, so if step is wrong, the user presses an arrow and thinks “why did it jump so far in one go”.
Scroll-wheel changes are an easy place for trouble. Rest the mouse over a number box and scroll the page, and the value changes even though the user never meant to. With many number boxes in a form this drives people mad. The only ways to avoid it are to put the number box farther from the scrolling area, or just use Slider instead — a slider doesn’t respond to the wheel.
precision affects the value itself, not the display. Type 2.567 with precision: 2 and the handler function gets 2.57. Changing only the display without changing the value would be a different matter, and there’s no switch for that here. For “keep full precision in the value, truncate only for display”, you have to format it yourself.
minimum, maximum, and step together decide “which values are legal”. For example, with minimum: 1 and step: 0.5, the legal values are 1, 1.5, 2, 2.5…; with minimum: 1 and step: 0.3, they are 1, 1.3, 1.6…. When you set these parameters, take a moment to ask whether that string of numbers is what you want, especially when you give all three at once. A combination that doesn’t line up leaves the browser permanently red, and the user can’t see what’s wrong.
Values like amounts of money, which can’t have binary rounding error, can be entered with Number, but don’t do the arithmetic with double. It passes a double to the handler function, so the whole 0.1 + 0.2 problem is still there. The approach is the same as in Chapter 3. The UI gives you a double; convert it to decimal the moment it reaches the business layer.
What the User Sees When an Out-of-Range Value Fails
Going out of minimum / maximum bounds is a poor experience. In Figure 6-4 the user types 9 and the input box only gets a red border. No text explains why it’s red. After clicking “Generate”, the two output positions on the right turn into “Error”, again with no explanation.
The only clue the user gets is that red border, and it appears “as soon as they finish typing”, not “only after clicking”. That’s actually an advantage — at least they don’t have to wait for submission. But it also means the range should be set a little wider: don’t write values that “shouldn’t occur in business terms” into maximum. A user who types 9 once in a while is just probing the boundary, and failing the whole event for that is too heavy. Leave the range for values that are “physically impossible” (a negative weight, a percentage over 100%), and put business rules in the handler function, where you can give a sentence in plain language.
The number box also has placeholder; after you clear it, a line of gray text appears in the box. Priority in the sample doesn’t have one, because the 1-to-5 range is obvious at a glance. If the range is hard to guess (say 0.5 to 3.5), writing placeholder: "0.5 – 3.5" is much friendlier than letting the user see a red border first.
There are a few easy traps on the empty-value side. Clear a number box and a non-nullable double parameter gets 0, with no error.
Cleared → Priority: 0
In the sample, “Priority” is a double, so after clearing, the card reads “Priority 0”. That 0 was converted from null; the user filled in nothing. To tell the two cases apart, declare the parameter as double?. Clearing then gives null, and typing 0 gives 0. Chapter 3 covered this rule; here you can see what it looks like on a real UI.
It’s even more obvious when the time box is left empty. A non-nullable System.DateTime parameter gets 0001-01-01 00:00, that is, default(DateTime). In the “Received values” section of Figure 6-3 the time line is filled in; clear the reminder time and click Generate again, and that line becomes 0001-01-01 00:00. This value raises no error and doesn’t warn you that “nothing was entered”; it just quietly appears on the card.
6.3 Slider: Values and Step Size
Slider and Number both pass a double to the handler function; the difference is how the value is obtained. Slider can only take values by step within a range, while Number accepts any number that passes validation.
var summary = gr.Slider(label: "Summary length", minimum: 10, maximum: 120, step: 10, value: 40, interactive: true);
This slider runs from 10 to 120 in steps of 10. It looks like a track, but there is actually a number box beside it. That box and the track are two ways of entering a value into the same component: drag the track to change the number, type a number to change the track.
The track snaps to the step. With a step of 10, the track has only the positions 10, 20, 30, 40…; force the track’s value to 33 and it lands on 30. The two positions nearest 33 are 30 and 40, and it takes the closer one. So you can’t drag a “33” out of the track.
The number box beside it doesn’t care. Type 33 straight into the number box and press Enter, and 33 is what gets submitted. The track jumps back to 30, the number box keeps 33, and the handler function gets 33. Like Number’s step, the number box only affects the increment and does no validation.
This property decides what Slider is good for: a fixed range and coarse adjustment. For quantities where “being a little off doesn’t matter”, like font size, opacity, and summary length, a slider beats a number box, because the user doesn’t have to think of a specific value — they drag until the number shown beside it looks right. The other way around, for a quantity like Priority that “must be an integer from 1 to 5”, Number fits better. A slider can do it too, but the user has to keep an eye on the number beside it.
value is the starting position. Without value, the slider stops at the lower bound. For a 10-to-120 slider, the initial value is 10. That’s usually not what you want (“Summary length 10” is too short), so always write value for a Slider.
You should use the slider’s info parameter; it adds a line of small text below the track. The track itself can only express “larger and smaller”; it can’t express “what this value means”. A line like “about how many characters per line” or “10 to 120, affects summary length” is more useful than making the user guess.
Dragging the track suits “getting a feel”, and typing a number suits “knowing you want 80”. Both ways change the same value, so you can treat the track as coarse adjustment and the number box as fine adjustment.
You can also operate a slider from the keyboard. After focusing it, the left and right arrow keys move one step per press; hold Shift and some browsers move ten steps. This matters for keyboard users, who can’t use a mouse-only UI.
Slider or Number
Both components pass a double to the handler function; which one you pick depends on “whether the user has a specific number in mind”.
| Scenario | Which to use | Reason |
|---|---|---|
| Font size, opacity, summary length | Slider | Being a little off doesn’t matter; dragging to find the feel is fastest |
| Priority, quantity, page number | Number | Must be a specific integer |
| A percentage with clear upper and lower bounds | Slider | The track itself is the “can’t go beyond” hint |
| Amounts, measurements | Number | Needs precise input a slider can’t give; convert to decimal in the business layer |
There’s one more practical difference: Slider has no “empty” state. It always has a value; if the user doesn’t drag it, the value is the one value gave. So you can’t use Slider where “this field may be left blank” — there’s no way to express “blank”. A cleared Number can express it (with double? you get null).
6.4 Code: Language, Line Wrapping, and Line Numbers
Code is a text box with highlighting; the value is still a string. What it adds is “how this text is displayed”: which language to highlight as, whether long lines wrap, and whether to draw line numbers.
var snippet = gr.Code(label: "Config snippet", language: "json", lines: 3, maxLines: 6, wrapLines: true, showLineNumbers: true, value: SampleCode, interactive: true);
lines and maxLines follow the same rules as Textbox: initial height and the upper bound for automatic growth. Paste in code longer than maxLines and the editor grows to the limit and stops; the rest takes scrolling to see. So how much you give maxLines depends on “how many lines you want visible at a glance”. Give it 6 lines and the user can probably see a whole function at once; give it 20 and the whole form gets stretched very tall.
wrapLines decides what happens to long lines. With it on, a long line folds onto the next line and the editor gets taller; with it off, long lines don’t fold and a horizontal scrollbar appears. It’s on in the sample. The config in Figure 6-2 doesn’t fit on one line and wraps into two; with it off, you’d have to drag horizontally to see the right half. A config snippet is meant to be read by people, and horizontal scrolling makes them miss the end.
showLineNumbers decides whether that column of line numbers on the left is drawn. Line numbers help when reading code (“the field on line 12”), but aren’t much use when reading config.
Dividing the Work Between Code and Textbox
Both components accept text and both pass a string; choosing between them comes down to one thing. Should this text be read as code?
Use Code for text that’s read as code (JSON, SQL, scripts, config files). It gives you a monospace font, syntax highlighting, line numbers, bracket matching, and a set of code-editor shortcuts (indent, comment, find). Together these make reading far easier than in a plain text box.
Use Textbox for text that isn’t read as code (body text, descriptions, logs). Turning on syntax highlighting for a passage of prose only makes it busier, and line numbers mean nothing there.
There’s one more use. Code with interactive: false works as read-only code display. It’s better than Textbox’s read-only mode because of the highlighting and line numbers, and less work than hand-assembling a piece of Markdown, since you don’t have to worry about backticks and escaping. Chapter 8 compares this again when it covers display components.
The Wrap-Lines Trade-off
Whether wrapLines is on or off depends on “how long a line of this code is”.
For things with a few dozen characters per line, like config files and SQL queries, wrapping on is more comfortable. Turn it off and long lines have to be dragged horizontally, so readers easily miss the right side. But for code where “one line is one complete expression”, wrapping off reads better, because folding cuts a statement up until you can’t see its structure.
The sample chooses on. That card is meant to be looked at, not copied and run; reading smoothly matters more than preserving the exact formatting.
A word on where language’s list comes from. Highlighting is done by the front end, and the front end only knows so many languages. You can still write a language that isn’t on the list; it just won’t be highlighted. But Code’s choice is to throw an exception, not fall back to plain text. So when you hit a language outside the list (C#, for example), either pick a close one (c) or don’t give language at all.
One more thing connects to Chapter 4: Code is not a form component. Chapter 4, on automatic form grouping, said that consecutive form components get wrapped into a form; Code isn’t among them and breaks the grouping up. In the sample, “Config snippet” sits between the Body and the Mark color, so the grouping there is cut in two by it. This has no effect on layout; it just adds one more break in the structure tree.
6.5 ColorPicker and DateTime
Both components have only one value, but the shapes of those values differ a lot.
ColorPicker passes a string to the handler function, of the form #3366cc.
var color = gr.ColorPicker(label: "Mark color", value: "#3366cc", interactive: true);
Click it open and you get a color palette; after choosing, the input box holds those seven characters. It makes no judgment about “whether the color looks good”, and it doesn’t accept color names like red. Once you’ve chosen, what you get is #rrggbb; if you never chose, it’s null. To use it, parse those seven characters in your own code.
In the sample this color is only written into the card’s footer (“Mark color #3366cc”); it doesn’t actually color anything. That’s deliberate. The Markdown component sanitizes HTML by default (Chapter 8), so stuffing <span style="color:..."> into it gets cleaned out. To really make the color take effect you have to go through CSS (Chapter 19), or use a component that supports styling. In this chapter, ColorPicker passes the handler function a seven-character string — not a color object and not a Color struct.
DateTime is a bit more complex; three parameters decide what it passes to the handler function.
var when = gr.DateTime(label: "Reminder time", type: "datetime", includeTime: true, timezone: "Asia/Shanghai", interactive: true);
type decides the type, and has only three legal values.
type | The handler function gets | The same moment (2026-11-20 09:30, Shanghai) |
|---|---|---|
timestamp (default) | long, Unix seconds | 1795138200 |
datetime | System.DateTime | 2026/11/20 09:30:00 |
string | string | "2026-11-20 09:30:00" |
The sample uses datetime, so the handler function signature writes System.DateTime when. Note that you have to write the full name: after using Gradio.Net;, DateTime refers to the component type, not System.DateTime. Writing DateTime when won’t compile, because that’s the component’s type.
includeTime decides whether the input box asks for hours, minutes, and seconds. Give it false and the hint in the box becomes YYYY-MM-DD, and only the date part is submitted.
Date only (type: string, includeTime: false) → "2026-11-20"
timezone decides how “the local time in the input box” is converted into a timestamp. Leave it out and the machine’s time zone is used. Fill in Asia/Shanghai and the 09:30 the user sees is understood as Shanghai time; open it on a machine in London and the same 09:30 is still treated as Shanghai time, so the timestamp doesn’t change. This parameter really takes effect only with type: "timestamp". datetime and string submit “that time literally”, with no time zone attached.
There’s one detail about the DateTime that datetime passes to the handler function: its Kind is Unspecified. The “Received values” section in Figure 6-3 reads “Time. 2026-11-20 09:30 (Unspecified)”. In other words, this object doesn’t know which time zone it belongs to. Using it as local time is fine, but before you use it for cross-time-zone conversion you have to add the time zone information first.
Choosing Among the Three Types
timestamp, datetime, and string correspond to three uses.
To store, compare, or sort, use timestamp. A long has no ambiguity: in a database it’s one integer column, adding and subtracting are seconds, and sorting is comparing magnitudes. The trouble is display; you have to convert it back to local time before showing it to the user.
To do date arithmetic in C# (add three days, get the first of the month), use datetime. What you get is a System.DateTime, so AddDays and ToString("yyyy-MM") work directly. The cost is that it carries the Unspecified time-zone marker, which you have to fill in before passing it across time zones.
To display and pass through exactly as entered, use string. If the user types 2026-11-20 09:30:00, the handler function gets exactly that string, down to the last character. It suits cases where “this time is only a label and needs no calculation” — like the “Reminder time” on the card, which is only written for people to read.
The sample uses datetime, because the card has to format it as yyyy-MM-dd HH:mm, and that’s the most direct way.
Time Zones
The timezone parameter is easy to overthink. It does exactly one thing: converts that string of local time in the input box into a timestamp using the specified time zone.
Fill in Asia/Shanghai, the user writes 09:30 in the box, and the framework treats it as Shanghai time and computes the matching timestamp. Leave it out and it uses this machine’s time zone.
Where it’s genuinely useful is “the machine’s time zone can change”. Use the program abroad and the system time zone changes with it, so the timestamp computed from the same 09:30 changes too. Hard-code Asia/Shanghai and the value stays stable.
includeTime: false is a separate matter. It narrows the input box to a date only, the placeholder changes from YYYY-MM-DD HH:MM:SS to YYYY-MM-DD, and the submitted value has no hours, minutes, or seconds either. Use it for fields that “only care which day”, like birthdays and deadlines; it saves the user the trouble of filling in 00:00:00.
The input format is fixed: YYYY-MM-DD, or YYYY-MM-DD HH:MM:SS with time. It doesn’t accept 2026/11/20 or “November 20” the way some people expect. Get the format wrong and the value isn’t accepted. This format takes some getting used to, but it’s unambiguous: month and day don’t swap places because of regional habits.
6.6 Input Component Values and Out-of-Range Behavior
The six components pass values of only three types to the handler function.
| Component | Type passed to the handler function | When empty |
|---|---|---|
Textbox (all three type values) | string | "" |
Number | double | 0, or null with double? |
Slider | double | Never empty, always has a value |
Code | string | "" |
ColorPicker | string | null |
DateTime | long / DateTime / string | null |
With this table you can write a handler function signature straight from it, without trial and error. The table in Chapter 3 was the “component → type” contract; this one extends it. The five extra components all have types that fall within these three.
Three Questions to Ask About Any Field
Choosing a component isn’t a matter of memorizing parameters; it’s a matter of asking three questions.
Question one. Is what the user fills in “free text” or “picked from a range”? Free text is Textbox; for picking from a range, look at how big the range is. Numbers use Number or Slider, colors use ColorPicker, times use DateTime. The next chapter adds the “picked from a set of options” kind too.
Question two. Does this value have a hard boundary it “must not exceed”? If it does, write it into the parameters (maxLength, minimum / maximum, step). If it doesn’t, don’t. Writing it anyway just gives the user a red box they can’t explain.
Question three, what does empty mean? Three answers: empty means “not filled in” (use a nullable type), empty means a default value (use a non-nullable type plus a default in code), or empty is treated as invalid (blocked in the parameters or in the business logic). Answer this clearly and the handler function’s signature is settled.
In the sample, the answers for the six fields are: the title and body are free text, and empty is invalid (an empty title leaves the card with no name); the config snippet is free text but read as code, and empty is allowed; the color and time are “picked from a range”, and empty means not filled in; summary length is a slider and has no empty state; priority empty means not set, represented by 0.
Handle Empty Values Uniformly
The six components behave differently when empty. Textbox and Code give an empty string, Number gives 0 or null, and ColorPicker and DateTime give null. If every handler function writes its own check, the same “not filled in” ends up with six different spellings.
The way to handle it is, unify them into one representation on the very first line of the handler function. For example, convert them all to string?, or check them all once before moving on to the business logic. The sample’s Compose doesn’t do this (it splices the received values straight into the card and shows blanks as blanks) because this module’s output is only a card, and an empty field doesn’t affect correctness. A module that really does validation (like the text cleanup in Chapter 5) should judge them all uniformly at the entry point and only then move on.
The empty-value shapes the components give aren’t uniform; your handler function should make them uniform.
Put this chapter’s six components into one signature and it looks like this.
(object, string) Compose(
string title,
string body,
string snippet,
string color,
System.DateTime when,
double summaryLength,
double priority,
string mail,
string pass)
Nine parameters for nine inputs. Three strings come from the three textboxes, snippet from Code, color from ColorPicker, when is a System.DateTime (type: "datetime"), summaryLength from Slider, priority from Number, and mail and pass are two more textboxes. If all the types line up, the function runs; if even one doesn’t, the UI just shows “Error”.
To know what type a component passes, look at its position in the signature.
Going out of range has four behaviors, all different.
Truncation. The part beyond maxLength never gets in at all, and the handler function receives the truncated value. This is the only out-of-range case that’s “handled automatically”.
Snapping. When you drag a Slider track, the value is pulled to the nearest step position (with a step of 10, 33 lands on 30). The number box isn’t subject to this.
Failure. A Number value beyond minimum / maximum turns the input box red, the event fails after the button is clicked, and the output positions are left with only “Error”. The handler function gets neither this value nor any other.
Let through. A Number’s step doesn’t line up (7.3 against a step of 0.5); the browser marks it invalid, but the value is submitted anyway. You have to check this kind yourself.
Put the four into a table, and when you hit an out-of-range value, check which kind it is first.
| Behavior | Who does it | Example | What the user sees |
|---|---|---|---|
| Truncation | The browser | maxLength exceeded | The extra characters can’t be typed in |
| Snapping | The browser | Drag a Slider track to 33 (step 10) | Lands on 30 |
| Failure | The browser + the framework | Number beyond maximum | Red border, only “Error” left after clicking the button |
| Let through | — | Number’s step doesn’t line up | Nothing happens, the value is submitted anyway |
Of these four, only “Failure” is a hard block. So when you use input components, think of boundaries in two places: what parameters can block (length, range) goes into the parameters; what parameters can’t block, or block too harshly (step, business rules), goes into the handler function.
One more rule of thumb. Wherever “not filled in” and “typed 0” have to be told apart, declare the parameter as double?. In the sample, Priority is written as double, so after clearing, the card shows 0. In a “1 to 5” priority that doesn’t matter, because 0 already means not set; but if the number were a “discount rate” or a “weight”, 0 and “not filled in” would be very far apart.
6.7 Chapter Summary
Textbox has three type values, and all submit a string. A password box only hides the display; the value is plaintext. lines is the initial height, maxLines is the upper bound for automatic growth, maxLength truncates hard in the browser, placeholder isn’t a value, and submitBtn adds a button inside the box that’s equivalent to Enter.
Number’s precision rounds before submission; going beyond minimum / maximum makes the whole event fail instead of clamping; step only affects the increment and takes no part in validation. When cleared, a non-nullable double gets 0; only double? gets null.
Slider can only take values by step, and a value off the step is snapped to the nearest legal one. It suits quantities with a fixed range and coarse adjustment; for precise input use Number.
Code’s language only recognizes a fixed list, which doesn’t include C#; a wrong value throws an exception at construction. wrapLines decides whether long lines fold or scroll horizontally, and showLineNumbers decides whether line numbers are drawn. Code isn’t a form component and breaks up form grouping.
ColorPicker passes the handler function a #rrggbb string. DateTime’s type decides whether the handler function gets a long timestamp, a System.DateTime, or a string; includeTime decides whether hours, minutes, and seconds are included; timezone only joins the conversion in timestamp mode. The object that datetime passes to the handler function has Kind Unspecified.
The six components’ values fall into three types: string, number, and time. Going out of range has four behaviors — truncation, snapping, failure, and letting through — and only “Failure” is a hard block. What parameters can block goes into the parameters; what they can’t goes into the handler function.
This chapter’s content, gathered into one note.
- For a text box, first decide single-line or multi-line, then whether you want
maxLength; a password box only hides the display, the value is plaintext. minimum/maximumon a number box are hard boundaries; going beyond fails the whole event.stepisn’t a boundary, just an increment.- A slider only takes values by step and suits coarse adjustment; for precision and for allowing empty, use a number box.
- A code box’s language only recognizes that list, which has no C#; set
wrapLinesandshowLineNumbersaccording to “who it’s for”. - A color gives a
#rrggbbstring; a time gives one oflong/DateTime/string. - Empty-value shapes aren’t uniform; make them uniform in the handler function.
The next chapter switches to a different batch of components. It lets the user pick from given options instead of typing freely. What’s hard about that batch isn’t the parameters; it’s “where the options come from, and what gets submitted after picking”.