Search code examples
htmllaraveliptextfield

text field for ip address in laravel


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 class="col-3 col-xs-3 col-sm-3 col-md-3 col-lg-3 col-xl-3 ">
        <div class="form-group">
            <label for="exampleFormControlSelect1" class="form-label text-truncate col-9">
            <input type="text" class="form-control" 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>  

Solution

  • 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