简体   繁体   中英

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

From react docs :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

This is why you don't see your change right after you're using setState.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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