Ionic-3 ion-input maxlength 属性不起作用

Posted

技术标签:

【中文标题】Ionic-3 ion-input maxlength 属性不起作用【英文标题】:Ionic-3 ion-input maxlength attribute not working 【发布时间】:2018-07-07 18:30:35 【问题描述】:

我尝试为 maxlengthmax 属性添加 ion-input ,但它没有按预期工作。

<ion-input type="number" placeholder="*" maxlength="1"></ion-input>

<ion-input type="number" placeholder="*" max="1"></ion-input>

任何人都知道相同的解决方案?

谢谢

【问题讨论】:

【参考方案1】:

据此贴:maxlength ignored for input type="number" in Chrome

Maxlength 不适用于输入 type="number"

这里建议另一种选择:https://github.com/ionic-team/ionic/issues/7072 dilhan119 建议使用 type="tel"

一个强大的解决方案是使用表单验证器,它会阻止表单提交(并且可以向用户显示错误):https://www.joshmorony.com/advanced-forms-validation-in-ionic-2/

【讨论】:

【参考方案2】:

我找到了出路,您可以在我的代码下方使用。很棒的一点是您可以保留输入类型编号,以便 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 更改为您喜欢的长度

【讨论】:

谢谢!这是我为我的项目创建“确认密码”验证器的完美方式【参考方案3】:
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);
        

【讨论】:

以上是关于Ionic-3 ion-input maxlength 属性不起作用的主要内容,如果未能解决你的问题,请参考以下文章

使用 Vue.js 从函数中的 <ion-input> 获取值

如何处理“Go”/“Enter”键盘按钮 Ionic2 <ion-input>

Ionic2 Ion-Input onSubmit 单击表单内的顶部按钮

Ionic 2 / Ionic 3 / Ionic 4:(懒惰)加载图片的微调器

markdown [Ionic 3 cheatsheet] #ionic

ionic 3 的内页不适用于 ionic 3 中的脚本或外部自定义 jQuery 插件