2

I'm trying to validate my file name and file extension using regular expression. My file name should only contain these characters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,_,.,@,-,(,), ' and my extension only should accept .txt files. My current function is pretty complicated and requires nested looping what I don't like. So I would like to check all of this in one single expression. Here is my current code:

fileName = 'My Document.txt'
fileExt = fileName.substr(fileName.length-4)
validCharList='A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,_,.,@,-,(,), ';
err = false;
letterOk = false;

    for(i=0;i<fileName.length;i++){
        letterOk = false;
        for(b=0;b<validCharList.length;b++){
            if(fileName.charAt(i) == validCharList.charAt(b)){
                letterOk = true;
                break;
            }   
        }

       if(letterOk == false){
            alert('file name has an invalid character.');
            return false;
            break;
       }
    }

if(fileExt != '.txt' && fileExt != '.TXT'){
     alert("Your document does not have a proper file extension.")
     return false;
} 

If anyone can help with this please let me know. Thanks!

2 Answers 2

8

Something like this?

return /^[a-z0-9_.@()-]+\.txt$/i.test(fileName);

If you want two separate checks, are you indicate in comments, you might do something like this:

var validFilename = /^[a-z0-9_.@()-]+\.[^.]+$/i.test(fileName);
var validExtension = /\.txt$/i.test(fileName);

The first expression tests everything up until the last period, and verifies that there is at least one non-period character after the last period, comprising the extension.

If you don't want to bother with the definition of what is a filename, you may instead invert the test, and explicitly check for the presence of invalid characters (here I'm testing the entire string again, so validFilename will be false even if you have invalid characters only in the extension - one way around that would be to validate extension before filename)

var validFilename = !/[^a-z0-9_.@()-]/i.test(fileName);
Sign up to request clarification or add additional context in comments.

15 Comments

Thanks! Regular expression above should cover upper/lower case too?
@WiktorStribiżew how correct expression looks like?
If you add more chars to the regex above, do not forget to keep hyphen at the end of the character class. Or add \ before it.
@espresso_coffee: Your extension test looks alright, but don't forget the /i, to ignore case. For the filename, you've forgotten the +, meaning it'll look for only a single character, and not a set of many characters matching the pattern. Another issue is that since you're losing the $, you're not testing the full string. Even with the +, you'd only be validating that the name starts with valid characters, not that it contains only valid characters. See my edited answer for a possible solution.
|
0

Try this for single line check of filename and extension using single regex.

 const validFilename = /^[\w,\s-]+\.[A-Za-z0-9]{3}$/i.test('filename');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.