简体   繁体   中英

Validate IP Address in React Native

I am looking for a way to validate ip adrress field (onChange) in my RN mobile app.

But it's taking both valid and invalid ip addresses and also number of digits in each part remains exact three.

Screenshot of App

I am using react-native-mask-input and so far I have tried this:

const ipMask = [
    [/\d/],
    [/\d/],
    [/\d/],
    '.',
    [/\d/],
    [/\d/],
    [/\d/],
    '.',
    [/\d/],
    [/\d/],
    [/\d/],
    '.',
    [/\d/],
    [/\d/],
    [/\d/],
  ];

<View style={{flexDirection: 'row'}}>
        <View style={{flex: 1, flexDirection: 'column'}}>
          <View style={{flexDirection: 'row'}}>
            <Text
              style={{
                fontFamily: 'Titillium-Semibold',
                color: Colors.grey_888888,
                fontSize: 14,
                marginLeft: 13,
              }}>
              IP Address *
            </Text>
          </View>
          <MaskInput
            value={ip}
            mask={ipMask}
            style={{
              marginLeft: 10,
              marginRight: 10,
              marginTop: 5,
              fontSize: 15,
              width: '95%',
              fontFamily: 'Titillium-Semibold',
              fontWeight: 'normal',
              paddingBottom: 0,
              height: 50,
              backgroundColor: '#FAFAFA',
              borderColor: Colors.grey_C0C0C0,
              borderWidth: 1,
              borderRadius: 5,
            }}
            onChangeText={(masked, unmasked, obfuscated) => {
              setIP(masked);
            }}
          />
          <Text
            style={{
              fontFamily: 'Titillium-Semibold',
              color: Colors.red_FF0000,
              fontSize: 11,
              marginLeft: 10,
            }}>
            {requiredMsg.ip && 'IP address is required !!!'}
          </Text>
        </View>
      </View>

Can anyone suggest me a way to validate ip address correctly?

Get the is-ip package from NPM. The link here can be helpful.

Then, you can simply use the functions to check. Eg:

isIP('192.168.0.1'); // returns true

You'll find more code sample in the webpage above.

EDIT: I just noticed the date of the question...:')

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