Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 413
Carter Roeser Avatar asked Nov 18 '16 23:11

Carter Roeser


People also ask

How do you specify a file type in HTML input?

<input type="file"> <input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission, or manipulated using JavaScript code and the File API.

How do I restrict input in HTML?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

Is URL valid input field in HTML?

The <input type="url"> defines a field for entering a URL. The input value is automatically validated before the form can be submitted. Tip: Always add the <label> tag for best accessibility practices!


2 Answers

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)">
like image 163
Commercial Suicide Avatar answered Sep 19 '22 04:09

Commercial Suicide


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">
like image 45
Kevin Doveton Avatar answered Sep 19 '22 04:09

Kevin Doveton