Link to home
Start Free TrialLog in
Avatar of erikTsomik
erikTsomikFlag for United States of America

asked on

validate file name using jquery

I need to validate a file name. For example index.html. It need to be done as addvalidator function.
No back slashes are allowed so /index.html is not valid
Avatar of Proculopsis
Proculopsis

Try something like this.
Avatar of erikTsomik

ASKER

how would I add it to a add.validator function
ASKER CERTIFIED SOLUTION
Avatar of Jon Norman
Jon Norman
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
JonNorman

the code does not work. basically no validation is triggering
Hi erik, you are either not using the plugin http://docs.jquery.com/Plugins/Validation or you are not then calling the method you have setup using validator.addMethod.
jQuery.validator.addMethod("filename", function(value, element) { 
  return this.optional(element) || /^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\";|/]+$/g.test(value); 
}, "Please specify a valid file name");
$("#myform").validate({
  rules: {
    fileName: "filename"
  }
});

Open in new window

Have a look at the documententation, this will show you how to set-up custom validator methods and look at the built in methods for how to use them.
I am using the method but I am  calling the method like this
rules: {
    fileName: "true"
  }
that to me says that the field with the name "fileName" is looking for a method called "true" to do the validation, if your field is named "fileName" you should do:
rules: {
    fileName: "filename"
  } 

Open in new window

Where filename (all lowercase) is the name of the method you have added, and fileName (java case) is the name of your field.
the reason I am asking is I need to do this validation conditionally, so if for example var x = 1 the validate filename other wise do not
Hi Erik,

I suggest that in the method you add you should do the conditional check:
jQuery.validator.addMethod("filenameOrxEquals1", function(value, element) { 
  return this.optional(element) || x==1 || /^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\";|/]+$/g.test(value); 
}, "Please specify a valid file name");
$("#myform").validate({
  rules: {
    fileName: "filename"
  }
});
...
rules: {
    fileName: "filenameOrxEquals1"
  } 

Open in new window

this sets up the method called filenameOrxEquals1 and then uses it in the rules for the fileName field.