Reputation: 875
So I have a text field on my web form, that users will use to enter a file path. I want to check if what is entered ends with .pdf
I have been looking around, and it looks like RegEx is what I need to use to get multiple browser support, but I couldn't find a good example.
HTML field
<input type="text" name="filelocation" id="filelocation" placeholder="Must include .pdf file extension">
Upvotes: 2
Views: 11432
Reputation: 1785
The regex sentence that work for me is the following
^[a-zA-Z�-ú0-9\s]{3,50}[.]{1}(([pP][dD][fF]))$
You can test it in the web site
Upvotes: 0
Reputation: 2727
You can use match
method to check if the name string has .pdf
at the end.
var fileName1 = "something.pdf";
var fileName2 = "other.pdf.not.valid";
var fileName3 = "somethingpdf";
var outputDiv = 'output';
validatePdfFileName(fileName1, outputDiv);
validatePdfFileName(fileName2, outputDiv);
validatePdfFileName(fileName3, outputDiv);
function validatePdfFileName(fileName, outputDivId) {
var outputDiv = document.getElementById(outputDivId);
if (fileName.match(/\.pdf$/)) {
outputDiv.innerHTML = outputDiv.innerHTML + "</br> valid pdf file name: " + fileName + " </br>";
} else {
outputDiv.innerHTML = outputDiv.innerHTML + "</br> invalid pdf file name: " + fileName + " </br";
}
}
<div id="output">Output</br></div>
Upvotes: 0
Reputation: 21965
Regex is probably the wrong tool for this. Try
var arr = path.split('.');
if (arr[arr.length - 1] === 'pdf') {
//do your thing
}
This should work fine in any browser.
If you prefer the regex solution (this isn't complicated enough for any performance comparison to matter, so its purely up to your taste) see CodeiSir's answer. It uses the HTML pattern attribute.
Upvotes: 3
Reputation: 3486
I agree that RegEx is probably not the best solution for this. Due to that, I recommend Jared Smith's answer. However, if you really want to use RegEx for this, give the following pattern a try:
var PdfPattern = /*\.pdf$/i;
This pattern will match any string that ends in ".pdf" with case insensitivity (e.g., "something.pdf" is equivalent to "something.PDF", "something.PdF", etcetera).
If you are asking about this with the intent to allow file uploads, then, for security reasons, you should also do server-side checks to make sure the uploaded file is actually a PDF. Doing checks client-side in Javascript is not sufficient for security.
Upvotes: 0
Reputation: 27275
The expression you need is /\.pdf$/
.
Example:
document.querySelector('#filelocation').addEventListener('blur', check);
function check(e) {
alert(/\.pdf$/.test(e.target.value));
}
<input type="text" name="filelocation" id="filelocation" placeholder="Must include .pdf file extension">
Upvotes: 0
Reputation: 13211
You can use the pattern attribute to do so:
<form action="#">
<input type="text" pattern=".+\.pdf$" placeholder="Must include .pdf file extension">
<input type="submit">
</form>
It will also assure that there is some text before the .pdf
at the end
Upvotes: 5