What would be a regular expression which I can use to match a valid JavaScript function name...
E.g. myfunction
would be valid but my<\fun\>ction
would be invalid.
[a-zA-Z0-9_])?
What is Validation? Validation is a method to authenticate the user. JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation. It is preferred by most of the web developers.
Validation functions are a powerful tool to ensure that only documents you expect end up in your databases. You can test writes to your database by content, by structure, and by user who is making the document request.
You can use javascript test() method to validate name field. The test() method tests for a match in a string.
This is more complicated than you might think. According to the ECMAScript standard, an identifier is:
an IdentifierName that is not a ReservedWord
so first you would have to check that the identifier is not one of:
instanceof typeof break do new var case else return void catch finally continue for switch while this with debugger function throw default if try delete in
and potentially some others in the future.
An IdentifierName starts with:
a letter the $ sign the _ underscore
and can further comprise any of those characters plus:
a number a combining diacritical (accent) character various joiner punctuation and zero-width spaces
These characters are defined in terms of Unicode character classes, so [A-Z]
is incomplete. Ä
is a letter; ξ
is a letter; 京
is a letter. You can use all of those in identifiers including those used for function names.
Unfortunately, JavaScript RegExp is not Unicode-aware. If you say \w
you only get the ASCII alphanumerics. There is no feasible way to check the validity of non-ASCII identifier characters short of carrying around the relevant parts of the Unicode Character Database with your script, which would be very large and clumsy.
You could try simply allowing all non-ASCII characters, for example:
^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With