2

I have some data (E.g.: 'acs24','45','ds' etc). Using this data I have the following method

function formatData(data) {
    var rege = /^([A-Za-z0-9_\-\.])$/;
    if ( rege.test(data) ) {
        alert('Alpaha Numeric data');
    }
}

But this is not working. What is wrong with this function?

Greg
  • 481
  • 1
  • 5
  • 21
Basavaraj Badiger
  • 269
  • 2
  • 9
  • 21

4 Answers4

1

Because it matches only one character.

var rege = /^([A-Za-z0-9_\-\.]+)$/;

This one matches at least one character.

Extra detail: The parentheses are not necessary here. They don't harm though.

Serge Wautier
  • 21,494
  • 13
  • 69
  • 110
1

Because it matches only one character and have an invalid range. If you want to allow hyphens, it need to be the last character in the regular expression list, otherwise it'll fail as _-. is an invalid range.

var rege = /^[A-Za-z0-9_.-]+$/;

Edit: Well, I pointed it before you've changed the question. :P

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
0

The following link has the anser

Anyway the answer is

"^[a-zA-Z0-9_]+$"

Your Regex would search for only 1 character ...

Community
  • 1
  • 1
Alphaneo
  • 12,079
  • 22
  • 71
  • 89
0

use + to match one or more characters

function formatData(data) {
    var rege = /^([A-Za-z0-9_\-\.])+$/;
    if ( rege.test(data) ) {
        alert('Alpaha Numeric data');
    }
}
Raynos
  • 166,823
  • 56
  • 351
  • 396