skip to Main Content

This is my code:

import React, { useState } from "react";

function IP() {
  const [ipAddress, setIPAddress] = useState("");

  const handleInputChange = (event) => {
    const inputValue = event.target.value;
    // Validate the input against IP address pattern
    const isValidIP = /^(d{1,3}.){3}d{1,3}$/.test(inputValue);

    if (isValidIP) {
      setIPAddress(inputValue);
    }

  };

  return (
    <div>
      <label>
        Enter IP Address:
        <input
          type="text"
          value={ipAddress}
          onChange={handleInputChange}
          placeholder="XXX.XXX.XXX.XXX"
        />
      </label>
      <p>Current IP Address: {ipAddress}</p>
    </div>
  );
}

export default IP

Here as you can see I’m just using regular expression to evaluate the input and to display it but the OnChange is not giving any error nor output. It’s not even changing the placeholder.

I tried to execute the regular expression individually and it is giving desired input but when added to my code it’s giving me false every single time.

4

Answers


  1. You should understand that on each letter input your handleInputChange will be called and IP will not be validated, so the value will be blank always as the default state is blank

    You need to package you IP address validation with a trigger to

    • Either allow the user to input full IP and then validate
    • Or have a button that triggers the validation

    Context:

    In react, whenever a form field is changed, the onChange event is triggered. : from docs

    The onChange event behaves as you would expect it to: whenever a form
    field is changed, this event is fired. It intentionally do not use the
    existing browser behavior because onChange is a misnomer for its
    behavior and React relies on this event to handle user input in real
    time. Taken from the docs:
    legacy.reactjs.org/docs/dom-elements.html#onchange

    Login or Signup to reply.
  2. The reason the input’s value doesn’t change is that it will only change if a string is valid after comparing against /^(d{1,3}.){3}d{1,3}$/ regular expression.
    There are 2 approaches to fix this:

    1. Execute setIPAddress(inputValue) on every onChange event, even if inputValue is not a valid IP address.
    2. If you want to set the value to ipAddress only if the string is a valid IP address, then you need to add an extra variable for the input’s state exclusively(it has to be executed on every onChange event), and the second variable to set the value to only if a string is a valid IP address.

    Regarding what approach you choose I recommend you add a mask to the input, it will make UX a way better for the user.

    Login or Signup to reply.
  3. The issue is you are setting the input only if it is a valid IP. This code => setIPAddress(e.target.value) will not be executed until you enter the correct IP. But as a user when you start typing that won’t be a valid IP until you enter the whole.

    Solution: (Not tested it, let me know if it does not work)

    I have created a state errors object(named errors) that will keep the form’s validation errors.

      const [ipAddress, setIPAddress] = useState("");
      const [errors, setErrors] = useState({});
    
      const handleInputChange = (event) => {
        const inputValue = event.target.value;
        setIPAddress(inputValue);
        setErrors({...errors, ipAddress: ''});
        const isValidIP = /^(d{1,3}.){3}d{1,3}$/.test(inputValue);    
        if (!isValidIP) {
           setErrors({...errors, ipAddress: 'Invalid IP'});
        } 
      };
    
     return (
        <div>
          <label>
            Enter IP Address:
            <input
              type="text"
              value={ipAddress}
              onChange={handleInputChange}
              placeholder="XXX.XXX.XXX.XXX"
            />
          </label>
          <p>{errors.ipAddress}</p> // show validation error here
          <p>Current IP Address: {ipAddress}</p>
        </div>
      );
    
    Login or Signup to reply.
  4. The problem in your implementation is that the ipAddress value is getting reset every time a user input event is triggered. So, the isValidIP regex is always returning false and the IPAddress p tag is not showing the IP Address regardless valid or not. Also, the regex has a missing escape for the dot (.) value. Correct regex validation will be:

    const isValidIP = /^(d{1,3}.){3}d{1,3}$/.test(inputValue);
    

    Solution Approach

    You can do following steps:

    • Add proper escaping of the dot (.) character in regex
    • Use another useState hook which will store the input state as you type
    • If an IP address is valid, then update the original hook value (ipAddress) with the new hook value (userInputValue), otherwise set it to default placeholder value (XXX.XXX.XXX.XXX)

    You can do something like the following:

    import React, { useState } from "react";
    
    function IP() {
      const [ipAddress, setIPAddress] = useState("");
      const [userInputValue, setUserInputValue] = useState("");
    
      const handleInputChange = (event) => {
        const inputValue = event.target.value;
        setUserInputValue(inputValue);
    
        // Validate the input against IP address pattern
        const isValidIP = /^(d{1,3}.){3}d{1,3}$/.test(userInputValue);
        if (isValidIP) {
          setIPAddress(userInputValue);
        } else {
          setIPAddress("XXX.XXX.XXX.XXX");
        }
      };
    
      return (
        <div>
          <label>
            Enter IP Address:
            <input
              type="text"
              value={userInputValue}
              onChange={handleInputChange}
              placeholder="XXX.XXX.XXX.XXX"
            />
          </label>
          <p>Current IP Address: {ipAddress}</p>
        </div>
      );
    }
    
    export default IP;
    
    

    Explanation

    Here I have used a second useState hook which will update the input as you type. If the regex pattern is matched with the input (that is, when the input is a valid IP Address), the ipAddress value will be set to input, and the p tag will show the valid IP. In the other case (when an IP address is invalid), the Current IP Address will show the default placeholder value (XXX.XXX.XXX.XXX).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search