Bob Tway
Bob Tway

Reputation: 9613

Set the jQuery validate to check for and allow empty file extensions

We're using jQuery validate to whitelist file extensions on a file upload :

$("#new-job-form").validate({
    focusCleanup: true,
    focusInvalid: false,
    ignore: [],
    rules: {
        jobServices: "required",
        file: {
            required: true,
            filesize: maxFileSize,
            extension: '.tsv|.txt|.csv|.psv|.xls|.xlsx|.zip|.7z|.rar'
        }
    }
});

This works fine. However, a new requirement has come in to accept files that dob't have an extension at all, and I can't figure out how to do this via JQuery validate. I tried adding an empty partition:

extension: '.txt|.csv|.xls|.xlsx|.zip|.7z|.rar||'

But that still refuses files without an extension.

Is there a way to configure the module to accept files with no extension ?

Upvotes: 0

Views: 2311

Answers (1)

Bourbia Brahim
Bourbia Brahim

Reputation: 14712

I suggest to you to create your own rule ; a rule same as extention but add the check if the file name doesn't contain a dot ,

value.indexOf('.') == -1;

see below snippet :

//adding extensionempty rule 
$.validator.addMethod("extensionempty", function(value, element, param) {

  param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif";
  console.log(value, param);
  return this.optional(element) || value.match(new RegExp("\\.(" + param + ")$", "i")) || value.indexOf('.') == -1;
}, $.validator.format("Please enter a value with a valid extension."));





$("#new-job-form").validate({
  focusCleanup: true,
  focusInvalid: false,
  ignore: [],
  rules: {
    file: {
      required: true,
      extensionempty: 'tsv|txt|csv|psv|xls|xlsx|zip|7z|rar'
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.js"></script>

<form id="new-job-form">
  <label for="file">.tsv|.txt|.csv|.psv|.xls|.xlsx|.zip|.7z|.rar  files allowed: </label>
  <input type="file" id="file" name="file">
  <br/>
  <input type="submit" value="Validate!">
</form>

Upvotes: 1

Related Questions