Home > Software engineering >  text field for ip address in laravel
text field for ip address in laravel

Time:06-14

what is the correct text field for IP address in HTML, I see some answers here but it did not work for me. Is there any alternative text field.

<div >
        <div >
            <label for="exampleFormControlSelect1" >
            <input type="text"  name="xproject" required pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"> 
            </label>
        </div>
    </div>  

CodePudding user response:

It depends on the browser you're testing it on. There is no official type="ip" support so you have to resort to type="text" with a regex pattern, or create a custom javascript solution that checks the input.

Some solutions are found here: Correct input type for IP Address

However, depending on your requirements you can simplify the design by just allowing any input, and make sure to validate it server side. If it's not an ip, the user would receive an error message. In Laravel it would look like this (link) (use any of the validation rules ip, ipv4 or ipv6) :

// SomeController.php
public function someAction(Request $request)
{
    $this->validate($request, [
        'ip' => 'required|ip',
    ];
}

CodePudding user response:

You can simply use a text (without pattern) input field if you want to keep things simple and do the validation on the back-end with Laravel:

$validated = $request->validate([
    'xproject' => 'required|ip'
]);

This will accept IP v4 and v6. If you only want ipv4, you can use the ipv4 rule and conversely ipv6 for ipv6.

'xproject' => 'required|ipv4'
'xproject' => 'required|ipv6'

Doc: https://laravel.com/docs/9.x/validation#rule-ip

However, if you also want to have a validation on the front-end, there are better solutions with some javascript depending what framework you use or lib. You can also use masks.

However, here is a solution that seems to work:

<input required pattern="^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$">

The solution comes from an updated answer in 2021 from @Oscar Camargo : https://stackoverflow.com/a/68177118/5282089

  • Related