How can I write an expression that checks for file extensions?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Haitashi
    New Member
    • Jun 2007
    • 96

    How can I write an expression that checks for file extensions?

    Hi:

    My task is very simple. I want to make sure that files that people are uploading have file extensions. File types don't matter, just that they have one. How would I write an expression for that?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    just retrieve the filename to a var:

    [CODE=javascript]var fn = 'your_filename. ext';
    [/CODE]
    then call a function like this:

    [CODE=javascript]function has_extension(f ile_name) {
    return /.{1}[\w\d]{2,}$/.test(file_name );
    }[/CODE]
    that checks for a fileextension with a minimum of 2 chars/nums ...

    kind regards

    Comment

    • Haitashi
      New Member
      • Jun 2007
      • 96

      #3
      Sweet. Thanks! =) ...

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        no problem ;) ... adapt it to your needs and post back to the forum anytime you have more questions ...

        kind regards

        Comment

        • Haitashi
          New Member
          • Jun 2007
          • 96

          #5
          Thanks again Gits. I had a do a very light fiddling with what you sent me. Just had to add a forward slash at the beginning. This is what is in my validation file:
          Code:
          function has_extension(file_name) {
            return /\.[(a-z|A-Z|0-1)]+$/.test(file_name);
          }
          I call it using the onSubmit from a form located in another page (naturally). One important thing to note is the "return" right before the call to the function. Without that there the form would submit no matter if the function would evaluate to true or false. Written the following way would result in the form not being submitted if the function returns "false".

          Code:
          onSubmit="return has_extension(document.getElementById('upload_input').value)"

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5390

            #6
            yes you are right ... the backslash is nessecary and when using the onsubmit event of a form for validation the return is nessecary here too ...

            well done :)

            kind regards

            Comment

            Working...