需求背景
登錄輸入手機號碼,進行驗證;需求要求輸入時只能輸入手機號碼,並在第三位和第七位進行空格隔開顯示;
效果
思路
antd form 中使用getValueFromEvent能夠對輸入值進行劫持改造,返回的數據會更新輸入框的值;
代碼
- 組件jsx
<Form.Item>
{getFieldDecorator("phoneNo", {
rules: [
{
required: true,
message: "請輸入您的手機號",
},
{ validator: checkPhone },
],
initialValue: "",
getValueFromEvent: phoneNoFormat,
})(<Input placeholder={"請輸入手機號"} />)}
</Form.Item>
- 劫持方法phoneNoFormat
// 只允許輸入數字並用空格隔開電話號碼
const phoneNoFormat = (e) => {
const val = e.target.value; // 舊值
let newVal = val.substring(0, 13).replace(/[^\d]/g, ""); // 提取中字符串中的數字(只數字)
// 檢測到第4位數字和第8位數字時,在第3位和第7位加入空格
// (注意:如果檢測到第3位數字和第7位數字時添加空格(判斷條件為>6和>2),刪除時會導致刪除到空格時無法繼續刪除,可自行嘗試)
if (newVal.length > 7) {
newVal = newVal.replace(/^(.{3})(.{4})(.*)$/, "$1 $2 $3");
} else if (newVal.length > 3) {
newVal = newVal.replace(/^(.{3})(.*)$/, "$1 $2");
}
// 返回格式化之后的值
return newVal;
};
- 驗證方法(驗證時需要去重空格)
const checkPhone = (rule, value, callback) => {
var reg = "^1[0-9]{10}$"; //手機號碼驗證regEx:第一位數字必須是1,11位數字
var re = new RegExp(reg);
// 去掉空格
const trueVal = value.replace(/\s*/g, "");
if (!trueVal) {
callback("請輸入您的手機號");
return;
}
if (!re.test(trueVal)) {
callback("請輸入正確的電話號碼");
return;
}
callback();
};