erikTsomik
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
No back slashes are allowed so /index.html is not valid
Try something like this.
ASKER
how would I add it to a add.validator function
Below is a link to the JQuery validator plugin, and followed by an example using a regexp
http://docs.jquery.com/Plugins/Validation/rules
http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation
http://docs.jquery.com/Plugins/Validation/rules
http://stackoverflow.com/questions/280759/jquery-validate-how-to-add-a-rule-for-regular-expression-validation
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
JonNorman
the code does not work. basically no validation is triggering
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"
}
});
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.
ASKER
I am using the method but I am calling the method like this
rules: {
fileName: "true"
}
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"
}
Where filename (all lowercase) is the name of the method you have added, and fileName (java case) is the name of your field.
ASKER
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:
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"
}
this sets up the method called filenameOrxEquals1 and then uses it in the rules for the fileName field.