2012-06-19 51 views
22

可能重複:
Limit file format when using <input type=「file」>?如何驗證HTML5只允許在'input type ='file''JPG,GIF或PNG?

我需要使用HTML5 pattern屬性只允許JPG,GIF和PNG文件在<input type="file">元素。

我現在有這個模式,但它不工作:

<input type="file" class="input-file" id="tbinstUploadFile0" name="tbinstUploadFile0" placeholder="Please insert an image file..." pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)"> 

這正則表達式是不兼容HTML5的?我如何測試有效的HTML5正則表達式模式?

最好的問候,

+2

在HTML5規範請參閱接受:http://dev.w3.org/html5/ spec/states-of-the-type-attribute.html#attr-input-accept – Qtax

回答

37

試着這麼做

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" /> 

點擊here for the latest browser compatibility table

現場演示here

只選擇圖像文件,你可以使用這個accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" /> 

現場演示here

Only gif, jpg and png will be shown, screen grab from Chrome version 44 只支持GIF,JPG和PNG將顯示,從Chrome版本屏幕抓取44

+0

它在Firefox 12中不受支持。感謝回覆。 –

+2

只能在2013年底在Chrome中運行。 – Rudy

+1

如果我將這個('accept =「image/jpg,image/jpeg,image/png」')添加到'input'標籤,它會向我顯示Firefox中的所有文件類型,如果我只是保持'accept =「image/*」',它就可以工作。我只想讓用戶選擇'jpg,jpeg'和'png'格式。 – sahil

相關問題