简体   繁体   中英

Check if string is a valid file name and path without Regx in angular Angular

I am trying to see if a string is a valid file name and path. Right now I am using regex to do it but seems after typing a longer length of string it uses lots of CPU and makes the browser to be un-progressive.

 public static readonly INVALID_FILE_NAME_REGEX: RegExp = /([a-zA-Z0-9 _@\-^!#$%&+={}./\\\[\]]+)+\.[a-zA-Z0-9]+$/;

and I use test to check it

INVALID_FILE_NAME_REGEX.test(myFilePath);

I was wondering if there is any way to check the file name and path is correct without Regex, or something does not use lots of resources?

here is example of valid and invalid paths.

invalid

path/
/path
/path/folder
/path/

valid

file.txt
/path/folder/file.txt
file.TXT

Thanks

Try this one:

/^[a-zA-Z0-9 _@\-^!#$%&+={}./\\\[\]]+\.[a-zA-Z0-9]+$/

Try wiht this, it worked for me.

^([\/][a-zA-Z0-9]+)*[\/]?[a-zA-Z0-9]+[.][a-zA-Z0-9]+$

Example 1: https://rubular.com/r/S7QydSU6jnuCLd

Example 2: https://rubular.com/r/sYARkEfsDJO15f

This page helps you to check you RegExp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM