自定义表单验证可以确保用户输入的数据符合要求。 @Entry @Component struct CustomFormValidationApp { @State username: string = ''; @State password: string = ''; @State formErrors: string[] = []; validateForm() { this.formErrors = []; if (this.username.length < 3) { this.formErrors.push('Username must be at least 3 characters long.'); } if (this.password.length < 6) { this.formErrors.push('Password must be at least 6 characters long.'); } return this.formErrors.length === 0; } build() { return ( <UI.Page> <UI.Label text="Custom Form Validation" /> <UI.TextField placeholder="Username" value={this.username} onValueChanged={(value) => this.username = value} /> <UI.TextField placeholder="Password" value={this.password} onValueChanged={(value) => this.password = value} type="password" /> {this.formErrors.map((error, index) => ( <UI.Label key={index} text={error} style={{ color: 'red' }} /> ))} <UI.Button text="Submit" disabled={this.formErrors.length > 0} onClick={() => { if (this.validateForm()) { console.log('Form is valid!'); } }} /> </UI.Page> ); } }本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。
自定义表单验证可以确保用户输入的数据符合要求。
本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。