-1

I need to get some javascript variable names from user. And user can enter only valid variable names. For instance:

"test1" - valid input,
"test 1" - not valid input.
"_a" - valid.

Now I am looking for php code which can validate user input with javascript variable naming standards.

mega6382
  • 9,211
  • 17
  • 48
  • 69
Nickolay
  • 35
  • 2
  • 8
  • 3
    have you tied regex? – madalinivascu Nov 13 '17 at 10:24
  • SO isn't a free coding service. You need to make an attempt to solve the issue yourself first. If you already have tried something, please share your code and explain where it goes wrong. – M. Eriksson Nov 13 '17 at 10:27
  • "Looking for code" is not an appropriate question. Please read [ask]. – evolutionxbox Nov 13 '17 at 10:29
  • Actually, I can use regex and check if input has character except numbers (after first), and _. And if it has - then is not valid input. But I hope to find more clarified code. – Nickolay Nov 13 '17 at 10:31
  • look at https://mothereff.in/js-variables , this may help – helpdoc Nov 13 '17 at 10:32
  • I need to see your full code. Anyway, the logic is to get user input(Post or Get method, what you used) and then with regex check the variable. I repeat, I need more code to help. – lisarko8077 Nov 13 '17 at 10:36
  • _"But I hope to find more clarified code"_ - As mentioned, if you have code, show us and let us know where it fails. If not, the question is off topic. – M. Eriksson Nov 13 '17 at 10:40
  • Related theme https://stackoverflow.com/questions/3980154/how-to-check-if-a-string-can-be-used-as-a-variable-name-in-php – Nickolay Nov 13 '17 at 15:01

1 Answers1

1

If you are not expecting any unicode values, here is a regex you can try:

if(preg_match('/^[a-zA-Z_$][0-9a-zA-Z_$]*$/', $jsVar, $matches)){
     var_dump($matches);
}

Regex Demo, PHP Demo

mega6382
  • 9,211
  • 17
  • 48
  • 69