Search code examples
javascriptregexhtml-input

How to use RegEx to check if form input ends with .pdf


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">

Solution

  • 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