Carter Roeser
Carter Roeser

Reputation: 360

HTML Input: Require URL to end in specific filetype

How can I make a URL Input form require the input to be both a valid URL, and end in a specific filetype.

For example, this is my input:

<input name="bg" placeholder="https://website.com/image" type="url">

As you can see, It is using the URL type, which restricts it to a valid http:// domain, but I would like the input field to only accept .png, .jpg, and .gif files.

Can this be achieved through html or javascript, and if so, how?

Thanks!

Upvotes: 16

Views: 1701

Answers (3)

Pradeep Kumar Das
Pradeep Kumar Das

Reputation: 891

Please go through the below code you will get the valid or invalid image url by blur the textbox.

function TextBoxChange()
{
var textboxValue=$("input[name=bg]").val();
var pattern=/https?:\/\/.*\.(?:png|jpg|gif)/i;
//alert(/https?:\/\/.*\.(?:png|jpg|gif)/i.test(textboxValue));
if(pattern.test(textboxValue))
{
$("#errorMsg").text("valid");
}
else
{
$("#errorMsg").text("invalid");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="bg" placeholder="https://website.com/image" onblur="TextBoxChange()" type="url" >
<label id="errorMsg"></label>

Upvotes: 2

Kevin Doveton
Kevin Doveton

Reputation: 396

You can achieve this using regex, you would also want to check this server side in case the user has disabled javascript.

Javascript

$("#imageUrl").change(function() {
    var t = $("#imageUrl").val()
    var expression = https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(.jpg|.png|.gif);
    var regex = new RegExp(expression);
    if (t.match(regex)) {
        alert("Successful match");
    } else {
        alert("No match");
    }
});

HTML

<input id="imageUrl" name="bg" placeholder="https://website.com/image" type="url">

Upvotes: 3

P.S.
P.S.

Reputation: 16384

You don't really need Javascript here, you can use pattern attribute for your input (i have added CSS just for example):

input:valid {
  border: 1px solid green;
}

input:invalid {
  border: 1px solid red;
}
<input name="bg" placeholder="https://website.com/image" type="url" pattern="https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(.jpg|.png|.gif)">

Upvotes: 17

Related Questions