You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-admin中使用TextInput实现手机号自动格式化?

Solution for Real-Time Phone Number Formatting in react-admin's TextInput

The issue with your current code is that you’re using phoneNumberFormat in the validate array—this only runs validation checks when the form is submitted, not real-time formatting as the user types. To achieve automatic formatting during input, you need to leverage react-admin’s built-in format and parse props for the TextInput component. Here’s how to fix it:

Step 1: Refine Formatting and Add Parsing Functions

First, update your formatting function to filter out non-numeric characters (so users can’t type invalid symbols) and keep the logic for adding dashes. Then add a parsing function to convert the formatted string back to a plain number for your backend:

// Format input to 123-456-7890 in real time
const formatPhoneNumber = (value) => {
  if (!value) return '';
  // Remove all non-digit characters first
  const digits = value.replace(/\D/g, '');
  // Apply segment-based formatting
  if (digits.length <= 3) return digits;
  if (digits.length <= 6) return `${digits.slice(0,3)}-${digits.slice(3)}`;
  return `${digits.slice(0,3)}-${digits.slice(3,6)}-${digits.slice(6,10)}`;
};

// Convert formatted number back to plain digits for backend submission
const parsePhoneNumber = (value) => {
  if (!value) return '';
  // Strip all dashes to get the raw numeric string
  return value.replace(/-/g, '');
};

Step 2: Update Validation Logic

Your validation should check the raw parsed value (not the formatted one) to ensure it’s a valid 10-digit number. Adjust your validate array:

const validatePhone = [
  required("Phone number is required"),
  (value) => {
    const rawNumber = parsePhoneNumber(value);
    if (rawNumber.length !== 10) {
      return "Phone number must be 10 digits";
    }
    return undefined; // Return undefined if validation passes
  }
];

Step 3: Configure the TextInput

Now pass the format, parse, and updated validate props to your TextInput:

<TextInput
  className="location-input"
  label="Cell phone"
  source="phone"
  format={formatPhoneNumber}
  parse={parsePhoneNumber}
  validate={validatePhone}
/>

How It Works

  • format: Runs on every input change, converting raw user input into the readable 123-456-7890 format that the user sees.
  • parse: Triggers when the form is submitted, converting the formatted string back to a plain numeric value (e.g., "1234567890") so your backend receives clean, unformatted data.
  • Validation: Checks the raw parsed number to ensure it’s exactly 10 digits, giving users immediate feedback if they enter an invalid length.

This approach ensures real-time formatting as users type, validates correctly, and sends consistent data to your backend.

内容的提问来源于stack exchange,提问作者Lawrence

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:25:48