4

I have "name" JavaScript variable. If variable "name" contains less than 4 characters I want to execute line: msg('name','Your name must contain minimum 4 characters.')'; I have tried something like this but it interpretated mathematical. Any idea? Thank you.

if(name < 4 ) {
  msg('name','Your name must contain minimum 4 characters.');
  return false;
}
pixelistik
  • 7,541
  • 3
  • 32
  • 42
CBuzatu
  • 745
  • 5
  • 16
  • 29
  • 1
    How is `name` declared? Probably `name.length` is what you're after, if `name` is a string variable. – Jared Farrish May 27 '12 at 01:58
  • 1
    Find a good javascript language reference site. That will help you with simple issues like this, PLUS you can learn a lot more by getting familiar with the language. – CM Kanode May 27 '12 at 02:00
  • So `Abe`, `Joe` and `Ron` isn't welcome? – some May 27 '12 at 03:49
  • nor are Ian, Bob, Jon, Ann....... in fact, if we're talking about validating names at all, you might want to read the answers here: http://stackoverflow.com/questions/3853346/how-to-validate-human-names-in-cakephp/3853820#3853820 – Spudley May 27 '12 at 13:40

4 Answers4

15
if (name.length < 4) {
   ...
}
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
8

You probably want to check the length of the string, not the numeric value of the string itself:

if(name.length < 4) {
    // ...
icktoofay
  • 126,289
  • 21
  • 250
  • 231
2
if(name.length < 4) {
    //Do something
}

You have to check the length of the variable.

Fun facts:

  • length can also be used to check the length of an Array
  • \n (new line) is also counted as a character.
icktoofay
  • 126,289
  • 21
  • 250
  • 231
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
1

Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and UTF-16 code points for this:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248