Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a JavaScript function name

Tags:

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_])? 
like image 683
Zoom Pat Avatar asked Jan 05 '10 18:01

Zoom Pat


People also ask

What are the JavaScript validation?

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.

What is function validate?

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.

How to validate name in js?

You can use javascript test() method to validate name field. The test() method tests for a match in a string.


1 Answers

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]*$ 
like image 198
bobince Avatar answered Oct 07 '22 18:10

bobince