如何在反应中使用 TextInput 格式化电话号码 - 管理员

Posted

技术标签:

【中文标题】如何在反应中使用 TextInput 格式化电话号码 - 管理员【英文标题】:How to format the phone number using TextInput in react - admin 【发布时间】:2021-04-06 19:53:52 【问题描述】:
const phoneNumberFormat = (num) => 
    let newNum = num.replace(/[-]+/g, '');
    let x;
    if (newNum.length <= 3) 
        x = newNum;
     else if (newNum.length > 3 && newNum.length <= 6) 
        x = newNum.slice(0, 3) + "-" + newNum.slice(3, 6)
     else 
        x = newNum.slice(0, 3) + "-" + newNum.slice(3, 6) + "-" + newNum.slice(6, 10)
    
    return x;
;
const validatePhone = [required("Phone number is required"), phoneNumberFormat];
<TextInput 
  className="location-input" 
  label="Cell phone" 
  source="phone" 
  validate=validatePhone 
/>

如果我输入电话号码,它将自动格式化为 123-456-7890,如果您有任何想法,欢迎您。

现在它只显示一条验证消息,但我需要自动格式化电话号码 123-456-7890

【问题讨论】:

我认为您不应该使用validate 属性来格式化电话号码,而是使用formatparse 方法而不是marmelab.com/react-admin/Inputs.html#common-input-props。 谢谢先生,它现在可以工作了。 【参考方案1】:
<TextInput 
className="location-input"
parse=phoneNumberFormat
label="Cell phone" 
source="phone" 
validate=validatePhone 
/>

【讨论】:

以上是关于如何在反应中使用 TextInput 格式化电话号码 - 管理员的主要内容,如果未能解决你的问题,请参考以下文章

如何在本机反应中验证 TextInput 值?

如何使用 DateTimePicker 值更新 TextInput?反应原生

在 ClearTextOnFocus 之后反应原生重置 TextInput

如何在TextInput中突出显示部分文本反应原生

如何将属性“OnChangeText”上的 TextInput 的“val”转换为 int。反应原生

当在反应本机中输入超过 6 个字符时,如何更改 textInput 文本中的字体大小?