1# TextInput 2 3The **\<TextInput>** component provides single-line text input. 4 5> **NOTE** 6> 7> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. 8 9 10## Child Components 11 12Not supported 13 14 15## APIs 16 17TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController}) 18 19**Parameters** 20 21| Name | Type | Mandatory | Description | 22| ----------------------- | ---------------------------------------- | ---- | --------------- | 23| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | 24| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.<br>If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, so as to prevent display errors when the component is updated.<br>Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md). | 25| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.| 26 27 28## Attributes 29 30Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. 31 32| Name | Type | Description | 33| ------------------------ | ---------------------------------------- | ---------------------------------------- | 34| type | [InputType](#inputtype) | Input box type.<br>Default value: **InputType.Normal** | 35| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.<br>The default value follows the theme. | 36| placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| 37| enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.<br>Default value: **EnterKeyType.Done**| 38| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.<br>Default value: **'#007DFF'** | 39| maxLength | number | Maximum number of characters in the text input. | 40| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.| 41| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| 42| showPasswordIcon<sup>9+</sup> | boolean | Whether to display the password icon at the end of the password text box.<br>Default value: **true**| 43| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style. For the inline input style, only **InputType.Normal** is supported.<br>Default value: **TextInputStyle.Default**| 44| textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**<br>**NOTE**<br>Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.<br>To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. | 45| selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.<br>If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.| 46| caretStyle<sup>10+</sup> | {<br>width: [Length](ts-types.md#length)<br>} | Caret style. It cannot be set in percentage. | 47| caretPosition<sup>10+</sup> | number | Caret position.| 48| showUnit<sup>10+</sup> | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.<br>By default, there is no unit.| 49| showError<sup>10+</sup> | string \| undefined | Error message displayed when an error occurs.<br>By default, no error message is displayed.<br>**NOTE**<br>If the parameter type is string and the input content does not comply with specifications, the error message is displayed. If the parameter type is undefined, no error message is displayed. See [Example 2](#example-2).| 50| showUnderline<sup>10+</sup> | boolean | Whether to show an underline. By default, the underline comes in the color of **'#33182431'**, thickness of 1 px, and input box size of 48 vp. The underline supports only the **InputType.Normal** type.<br>Default value: **false**| 51| passwordIcon<sup>10+</sup> | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.<br>By default, the system-provided icon is used.| 52| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true** | 53| selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**| 54| barState<sup>10+</sup> | [BarState](ts-appendix-enums.md#BarState) | Scrollbar state when the inline input style is used.<br>Default value: **BarState.Auto**| 55| maxLines<sup>10+</sup> | number | Maximum number of lines that can be displayed when the inline input style is used.<br>Default value: **3**| 56| customKeyboard<sup>10+</sup> | [CustomBuilder](ts-types.md#custombuilder8) | Custom keyboard.<br>**NOTE**<br>When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method, and the **enterKeyType** attribute setting for the system keyboard will not take effect.<br>The custom keyboard's height can be set through the **height** attribute of the custom component's root node, and its width is fixed at the default value.<br>The custom keyboard is displayed on top of the current page, without compressing or raising the page.<br>The custom keyboard cannot obtain the focus, but it blocks gesture events.<br>By default, the custom keyboard is closed when the input component loses the focus. You can also use the [TextInputController](#textinputcontroller8).[stopEditing](#stopediting10) API to close the keyboard.| 57> **NOTE** 58> 59> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: <br>{<br> top: 8 vp,<br> right: 16 vp,<br> bottom: 8 vp,<br> left: 16 vp<br> } 60> 61> Since API version 10, **.width('auto')** can be set for the **\<TextInput>** component. Under this setting, the component auto-adapts its width to the text width, while respecting the **constraintSize** configuration and the maximum and minimum width restrictions received by the parent container. For details, see [Size](ts-universal-attributes-size.md#attributes). 62 63## EnterKeyType 64 65| Name | Description | 66| ------------------- | --------- | 67| Go | The Enter key is labeled "Go." | 68| Search | The Enter key is labeled "Search." | 69| Send | The Enter key is labeled "Send." | 70| Next | The Enter key is labeled "Next."| 71| Done | The Enter key is labeled "Done." | 72 73## InputType 74 75| Name | Description | 76| ------------------ | ------------- | 77| Normal | Normal input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters.| 78| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default. The password input mode does not support underlines.| 79| Email | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.| 80| Number | Digit input mode. | 81| PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.| 82 83## TextInputStyle<sup>9+</sup> 84 85| Name | Description | 86| ------------------ | ------------- | 87| Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | 88| Inline | Inline input style. The background height of the selected text is the same as the height of the text box.<br>This style is used in scenarios where editing and non-editing states are obvious, for example, renaming in the file list view.<br>The **showError** attribute is not supported for this style.| 89 90## PasswordIcon<sup>10+</sup> 91 92| Name | Type | Mandatory| Description | 93| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- | 94| onIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to hide the password in password input mode.| 95| offIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to show the password in password input mode.| 96 97## Events 98 99In addition to the [universal events](ts-universal-events-click.md), the following events are supported. 100 101| Name | Description | 102| ------------------------------------------------------------ | ------------------------------------------------------------ | 103| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br>**value**: text content.<br>This event is triggered when any of the following conditions is met:<br>1. Keyboard input is received.<br>2. Paste and cut is performed.<br>3. Ctrl+V is pressed.| 104| onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.<br>**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype).| 105| onEditChanged(callback: (isEditing: boolean) => void)<sup>(deprecated)</sup> | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended.| 106| onEditChange(callback: (isEditing: boolean) => void)<sup>8+</sup> | Triggered when the input status changes. When the cursor is placed in the text box, it is in the editing state. Otherwise, it is in the non-editing state. If the value of **isEditing** is **true**, text input is in progress.| 107| onCopy(callback:(value: string) => void)<sup>8+</sup> | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.| 108| onCut(callback:(value: string) => void)<sup>8+</sup> | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.| 109| onPaste(callback:(value: string) => void)<sup>8+</sup> | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.| 110| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)<sup>10+</sup> | Triggered when the text selection position changes.<br>**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.<br>**selectionEnd**: end position of the text selection area.| 111| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)<sup>10+</sup> | Triggered when the text content is scrolled.<br>**totalOffsetX**: X coordinate offset of the text in the content area.<br>**totalOffsetY**: Y coordinate offset of the text in the content area.| 112 113## TextInputController<sup>8+</sup> 114 115Implements the controller of the **\<TextInput>** component. 116 117### Objects to Import 118``` 119controller: TextInputController = new TextInputController() 120``` 121### caretPosition<sup>8+</sup> 122 123caretPosition(value: number): void 124 125Sets the position of the caret. 126 127**Parameters** 128 129| Name| Type| Mandatory| Description | 130| ------ | -------- | ---- | -------------------------------------- | 131| value | number | Yes | Length from the start of the string to the position where the caret is located.| 132### setTextSelection<sup>10+</sup> 133 134setTextSelection(selectionStart: number, selectionEnd: number): void 135 136Sets the text selection area, which will be highlighted. 137 138**Parameters** 139 140| Name | Type| Mandatory| Description | 141| -------------- | -------- | ---- | ---------------------- | 142| selectionStart | number | Yes | Start position of the text selection range. The start position of text in the text box is 0.| 143| selectionEnd | number | Yes | End position of the text selection range.| 144 145### stopEditing<sup>10+</sup> 146 147stopEditing(): void 148 149Exits the editing state. 150 151### getTextContentRect<sup>10+</sup> 152 153getTextContentRect(): [RectResult](#rectresult10) 154 155Obtains the position of the edited text area relative to the component and its size. The unit of the return value is pixel. 156 157**Return value** 158 159| Type | Description | 160| ------------------- | -------- | 161| [RectResult](#rectresult10) | Position of the edited text area relative to the component and its size.| 162 163> **NOTE** 164> 165> - If no text is entered, the return value contains the position information, but the size is 0. 166> - The position information is the offset of the first character relative to the editable area. 167 168### RectResult<sup>10+</sup> 169 170Describes the position and size. 171 172| Parameter | Type | Description| 173| ------- | ------ | ----------------------- | 174| x | number | X coordinate.| 175| y | number | Y coordinate.| 176| width | number | Content width.| 177| height | number | Content height.| 178 179 180### getTextContentLineCount<sup>10+</sup> 181 182getTextContentLineCount(): number 183 184Obtains the number of lines of the edited text. 185 186**Return value** 187 188| Type | Description | 189| ----- | -------- | 190| number| Number of lines of the edited text.| 191 192## Example 193 194### Example 1 195 196```ts 197// xxx.ets 198@Entry 199@Component 200struct TextInputExample { 201 @State text: string = '' 202 controller: TextInputController = new TextInputController() 203 204 build() { 205 Column() { 206 TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller }) 207 .placeholderColor(Color.Grey) 208 .placeholderFont({ size: 14, weight: 400 }) 209 .caretColor(Color.Blue) 210 .width(400) 211 .height(40) 212 .margin(20) 213 .fontSize(14) 214 .fontColor(Color.Black) 215 .inputFilter('[a-z]', (e) => { 216 console.log(JSON.stringify(e)) 217 }) 218 .onChange((value: string) => { 219 this.text = value 220 }) 221 Text(this.text) 222 Button('Set caretPosition 1') 223 .margin(15) 224 .onClick(() => { 225 // Move the caret to after the first entered character. 226 this.controller.caretPosition(1) 227 }) 228 // Password text box. 229 TextInput({ placeholder: 'input your password...' }) 230 .width(400) 231 .height(40) 232 .margin(20) 233 .type(InputType.Password) 234 .maxLength(9) 235 .showPasswordIcon(true) 236 // Inline-style text box. 237 TextInput({ text: 'inline style' }) 238 .width(400) 239 .height(50) 240 .margin(20) 241 .borderRadius(0) 242 .style(TextInputStyle.Inline) 243 }.width('100%') 244 } 245} 246``` 247 248 249 250### Example 2 251 252```ts 253@Entry 254@Component 255struct TextInputExample { 256 @State PassWordSrc1: Resource = $r('app.media.onIcon') 257 @State PassWordSrc2: Resource = $r('app.media.offIcon') 258 @State TextError: string = '' 259 @State Text: string = '' 260 @State NameText: string = 'test' 261 262 @Builder itemEnd() { 263 Select([{ value: 'KB' }, 264 { value: 'MB' }, 265 { value: 'GB' }, 266 { value: 'TB', }]) 267 .height("48vp") 268 .borderRadius(0) 269 .selected(2) 270 .align(Alignment.Center) 271 .value('MB') 272 .font({ size: 20, weight: 500 }) 273 .fontColor('#182431') 274 .selectedOptionFont({ size: 20, weight: 400 }) 275 .optionFont({ size: 20, weight: 400 }) 276 .backgroundColor(Color.Transparent) 277 .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' }) 278 .onSelect((index: number) => { 279 console.info('Select:' + index) 280 }) 281 } 282 283 build() { 284 Column({ space: 20 }) { 285 // Customize the password icon. 286 TextInput({ placeholder: 'Custom password icon' }) 287 .type(InputType.Password) 288 .width(380) 289 .height(60) 290 .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 }) 291 // Show an underline. 292 TextInput({ placeholder: 'Underline style' }) 293 .showUnderline(true) 294 .width(380) 295 .height(60) 296 .showError('Error') 297 .showUnit(this.itemEnd) 298 299 Text (`User name: ${this.Text}`) 300 .width('95%') 301 TextInput({ placeholder: 'Enter user name', text: this.Text }) 302 .showUnderline(true) 303 .width(380) 304 .showError(this.TextError) 305 .onChange((value: string) => { 306 this.Text = value 307 }) 308 .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed. 309 if (this.Text == this.NameText) { 310 this.TextError = '' 311 } else { 312 this.TextError ='Incorrect user name.' 313 this.Text = '' 314 } 315 }) 316 317 }.width('100%') 318 } 319} 320``` 321 322 323 324### Example 3 325 326```ts 327// xxx.ets 328@Entry 329@Component 330struct TextInputExample { 331 controller: TextInputController = new TextInputController() 332 @State inputValue: string = "" 333 334 // Create a custom keyboard component. 335 @Builder CustomKeyboardBuilder() { 336 Column() { 337 Button('x').onClick(() => { 338 // Disable the custom keyboard. 339 this.controller.stopEditing() 340 }) 341 Grid() { 342 ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item:number|string) => { 343 GridItem() { 344 Button(item + "") 345 .width(110).onClick(() => { 346 this.inputValue += item 347 }) 348 } 349 }) 350 }.maxCount(3).columnsGap(10).rowsGap(10).padding(5) 351 }.backgroundColor(Color.Gray) 352 } 353 354 build() { 355 Column() { 356 TextInput({ controller: this.controller, text: this.inputValue }) 357 // Bind the custom keyboard. 358 .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }) 359 } 360 } 361} 362``` 363 364 365