我曾尝试为ion-input
,maxlength
属性添加max
,但它没有按预期运行。
<ion-input type="number" placeholder="*" maxlength="1"></ion-input>
<ion-input type="number" placeholder="*" max="1"></ion-input>
任何人都知道相同的解决方案吗?
谢谢
答案 0 :(得分:13)
根据这篇文章:maxlength ignored for input type="number" in Chrome
Maxlength对输入类型=“数字”
不起作用这里建议了一个替代方案:https://github.com/ionic-team/ionic/issues/7072 其中dilhan119建议使用type =“tel”
一个强大的解决方案是使用表单验证器,这将阻止表单提交(并可以向用户显示错误):https://www.joshmorony.com/advanced-forms-validation-in-ionic-2/
答案 1 :(得分:0)
我找到了出路,可以在我的代码下面使用。很棒的是,您可以保留输入类型的编号,以便android将显示您想要的键盘
将此代码放入表单构建器
phone: ['', [Validators.required, this.isValidNumber.bind(this)]]
在您的ts文件中,添加以下方法
isValidNumber(fieldControl: FormControl) {
if(this.formBuilderGroup) {
return fieldControl.value.toString().length < 10 ? null : {
NotEqual: true
};
}
}
在上面的代码中将formBuilderGroup更改为您的表单构建器组名称 是。将10更改为您喜欢的长度
答案 2 :(得分:0)
HTML:
<ion-textarea [(ngModel)]=“text” (ionChange)="textareaMaxLengthValidation()"></ion-textarea>
<ion-input type="text" [(ngModel)]=“text” (ionChange)="textareaMaxLengthValidation()"></ion-input>
TS:
textareaMaxLengthValidation() {
if (text.length > 50) {
text= text.slice(0, 50);
}