Search code examples
jqueryjquery-validation-engine

How to validate filename in jQuery-Validation-Engine?


How to validate a filename in jQuery-Validation-Engine with no special characters allowed except for underscore (_)?

I tried these regex: /^[a-zA-Z\d._]*$/ and /^[a-zA-Z0-9_]+$/ but no luck. The regex are valid based on https://regexr.com/

Here's my sample:

"validFileName": {
  "regex": /^[a-zA-Z\d._]*$/,
  "alertText": "* Invalid filename"
},
            

Input tag:

<input type="file" name="attachment" id="attachment" class="validate[required, custom[validFileName]]"/>

Solution

  • I finally got it. I'll post it here in-case someone need it. I used the call function:

    html:

    <input class="validate[required, funcCall[validFilename]]" type="file" name="attachment" id="attachment" />
    

    script:

    function validFilename(field, rules, i, options) {
        var uploadedFile = $(field);
        
        if (uploadedFile) {
        var extensions = rules[i + 1];               
        var mimeFilter = new RegExp(extensions);
        var file = document.getElementById('attachment').files[0].name;
        var pattern = new RegExp(/^[a-zA-Z0-9_.]+$/);
        
             if (!pattern.test( file ) ) {
                  return '"' + file +  '" filename is invalid. No special character allowed.';
             }
            
        }
    
    }
    

    here's my working code: https://jsfiddle.net/26jkLhr9/

    I know it is not the best answer but it worked! If you have a better and clean idea you are welcome to add it here.