如何在React JS中实现带国际区号的标准化手机号输入组件
React 全球手机号输入功能实现方案
实现逻辑
- 基于成熟的手机号输入组件
react-phone-number-input实现全球区号支持 - 输入阶段自动过滤括号、多空格等非法字符
- 提交前统一格式化输出,保证数据库存储格式完全统一
操作步骤
- 安装所需依赖
npm install react-phone-number-input libphonenumber-js --save
- 替换原有Login组件代码,完整修改后代码如下:
import React from 'react' import firebase from './firebase' import "./App.css"; import { getDatabase, ref, child, get } from "firebase/database"; // 引入手机号输入组件和样式 import PhoneInput from 'react-phone-number-input' import 'react-phone-number-input/style.css' import { parsePhoneNumber } from 'libphonenumber-js' class Login extends React.Component { // 初始化state state = { mobile: '', otp: '' } handlePhoneChange = (value) => { // value已经是过滤了非法字符的标准值,直接存state this.setState({ mobile: value }, () => { console.log(this.state.mobile); }); } handleChange = (e) =>{ const {name, value } = e.target this.setState({ [name]: value }) } configureCaptcha = () =>{ window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', { 'size': 'invisible', 'callback': (response) => { this.onSignInSubmit(); }, } ); } onSignInSubmit = (e) => { e.preventDefault() // 提交前统一格式化手机号 let formattedPhone = '' try { const parsedNumber = parsePhoneNumber(this.state.mobile) // 此处可自定义输出格式: // 1. 带1个空格格式:+91 7896541230 formattedPhone = `+${parsedNumber.countryCallingCode} ${parsedNumber.nationalNumber}` // 2. 连写格式:+917896541230,需要的话注释上面一行,解开下面一行即可 // formattedPhone = `+${parsedNumber.countryCallingCode}${parsedNumber.nationalNumber}` } catch (err) { alert('请输入有效的手机号格式') return } this.configureCaptcha() const appVerifier = window.recaptchaVerifier; const dbRef = ref(getDatabase()); get(child(dbRef, `Users/${formattedPhone}`)).then((snapshot) => { if (snapshot.exists()){ firebase.auth().signInWithPhoneNumber(formattedPhone, appVerifier) .then((confirmationResult) => { window.confirmationResult = confirmationResult; alert('An OTP has been sent to your registered mobile number') localStorage.setItem("Phone_No", formattedPhone ) console.log(localStorage.getItem('Phone_No')); }).catch((error) => { console.error(error); alert("Oops! Some error occured. Please try again.") }); } else{ alert('Sorry, this mobile number is not registered with us. Please use your registered mobile number.'); } }) } onSubmitOTP = (e) =>{ e.preventDefault() const code = this.state.otp window.confirmationResult.confirm(code).then((result) => { const Users = result.user; console.log(JSON.stringify(Users)) this.props.history.push("/home"); }).catch((error) => { alert("You have entered wrong code") }); } render() { return ( <div className="Main-header"> <img src="./55k-logo.png" alt="Company Logo" style={{height: "80px", width: "200px"}} /> <br/> <div> <h2>Login Form</h2> <p>Limtless Water. From Unlimited Air.</p> <form onSubmit={this.onSignInSubmit}> <div id="sign-in-button"></div> <label>Mobile Number</label> <br/> {/* 替换原有input为手机号组件 */} <PhoneInput placeholder="Enter Your Number" value={this.state.mobile} onChange={this.handlePhoneChange} required id="phone" /> <div className="buttons"> <button type="submit">Submit</button> </div> </form> </div> <div> <form onSubmit={this.onSubmitOTP}> <label >Code</label> <br/> <input type="number" name="otp" placeholder="Enter The 6 Digit OTP" required onChange={this.handleChange}/> <div className="buttons" > <button type="submit">Submit</button> </div> </form> </div> </div> ) } } export default Login;
格式说明
你可以根据需求自由切换存储格式,只需要修改onSignInSubmit函数中formattedPhone的拼接规则即可,两种格式都不会出现括号、多空格等非法字符,完全符合要求。
内容的提问来源于stack exchange,提问作者MOHAMMAD ZEESHAN
相关产品推荐
相关产品推荐

