如何使用HTML5使用模式属性仅验证CSV文件上传


How can I validate for only CSV file uploads using the pattern attribute using HTML5?

我的HTML看起来像这样:

<form>
    <input type="file" name="txtFile" pattern="?" id="txtFile" class="required"/>
</form>
pattern = '?'

使用哪个正则表达式,我将添加ONLY CSV FILE ALLOW的验证。

如果我上传.xls或任何其他文件,它将显示一个错误。

现在您可以使用新的HTML5输入验证属性:

pattern="^.+'.(xlsx|xls|csv)$"

接受其他文件的类型(参考:HTML5文档):

对于CSV:

<input type="file" accept=".csv" />

对于Excel文件,2003-2007(.xls):

<input type="file" accept="application/vnd.ms-excel" />

对于Excel文件,2010(.xlsx):

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

对于文本文件(.txt):

<input type="file" accept="text/plain" />

对于图像文件(.png、.jpg等):

<input type="file" accept="image/*" />

对于HTML文件(.htm,.HTML):

<input type="file" accept="text/html" />

对于视频文件(.avi、.mpg、.mpeg、.mp4):

<input type="file" accept="video/*" />

对于音频文件(.mp3、.wav等):

<input type="file" accept="audio/*" />

对于PDF文件,请使用:

<input type="file" accept=".pdf" /> 

只接受其中一种文件类型并不容易。它取决于不同的操作系统和安装的文本阅读程序。在Unix类型的系统中,如果您传递.csv文件,您将获得.csv文件类型,但如果您在Windows上传递相同的文件,则将获得不同的文件类型,例如text/comma-separated-values, text/csv, application/csv, application/excel, application/vnd.ms-excel, application/vnd.msexcel, text/anytext

它调用mime-types,并且对于任何文本类型的文件都可以不同。这是你可以阅读更多内容的链接。

使用此:

<input type="file" name="txtFile" id="txtFile" class="required" accept=".csv,text/csv" />

提到MIME类型是一种很好的做法。

试试这个:

<input type="file" name="txtFile" accept=".csv" id="txtFile" class="required" />