简体   繁体   English

在 React.js 上验证电话号码

[英]Validate phone number on React.js

I'm trying to validate the phone field, to get all letters and dots with the code below.我正在尝试验证电话字段,以使用以下代码获取所有字母和点。

validatePhone = () => {
        const sanitizedPhone = this.state.phone.replace(/\D/g, '');
        if (sanitizedPhone.length >= 10 && sanitizedPhone.length <= 11) {
            this.setState({ phone: sanitizedPhone });
            return true;
        }
        toast.error('Invalid phoneNumber.', {
            position: "top-center",
            autoClose: false,
            closeOnClick: true,
        });
        return false;
    }

When i trying console.log(sanitizedPhone) with dots in input like 11.97.4.4.51234 i get 11974451234 but after this, on console.log(this.state.phone) i get the older number 11.97.4.4.51234当我尝试使用像11.97.4.4.51234这样的输入点的console.log(sanitizedPhone) ,我得到11974451234但在此之后,在console.log(this.state.phone)我得到旧号码11.97.4.4.51234

From react docs :反应文档

setState() does not always immediately update the component. setState() 并不总是立即更新组件。 It may batch or defer the update until later.它可能会批量更新或推迟更新。 This makes reading this.state right after calling setState() a potential pitfall.这使得在调用 setState() 之后立即读取 this.state 成为一个潜在的陷阱。

This is why you don't see your change right after you're using setState.这就是为什么您在使用 setState 后没有立即看到更改的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM