-1

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]]"/>
mrrsb
  • 663
  • 3
  • 13
  • 28

2 Answers2

0

Try to use this regex pattern- ([a-zA-Z\d._])\w+

And change the class in input element as below-

class="validate[required,custom[email]] text-input"

Also have look at this for reference to create custom rule- How to create simple custom rule?

praveen kaushik
  • 116
  • 1
  • 5
  • 1
    The issue isn't the regex (and yours *still* as the `.` to allow any character) - it's that jquery-validation-engine doesn't work with `type='file'` – freedomn-m Jun 29 '20 at 08:51
  • I got the idea of getting the filename by using javascript code (e.target.files[0].name) only then reinvent it to jquery-validation-engine, would it possible. but I don't know how to apply in on script. – mrrsb Jun 30 '20 at 03:14
  • By the way @praveen your answer is for jQuery Validate Plugin. But thanks for the headsup. – mrrsb Jun 30 '20 at 05:33
0

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.

mrrsb
  • 663
  • 3
  • 13
  • 28