-2

I have created a function that checks to see if a input text field is valid and then either append a class name to the element that will correspond to some css code or do nothing if it is valid.

function checkInputText(inputType, elem, oldClass, classError) {
    var inputT = document.getElementById(elem);
    var oldClass = oldClass;
    var b = regex[inputType].test(inputT.value)
    if (!b) {
        inputT.className = classError + ' ' + oldClass;
        return false;
    } else {
        inputT.className = oldClass;
    }
}

However, for some unknown reason, when the function calls the .test() function it returns true for an event the first time, but when you try it again it returns false.

The full code is here http://jsfiddle.net/assuredlonewolf/cscyB/2/

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
James Fair
  • 598
  • 1
  • 7
  • 18
  • 3
    Just so you know, this line `var oldClass = oldClass;` doesn't do anything. – Paul Apr 10 '12 at 02:02
  • Regardless of the problem, put a semicolon at the end of the .test line - it might not be the cause to your problem, but it's a must anyway. – Ofer Zelig Apr 10 '12 at 02:05
  • 1
    [Semicolons in JavaScript are optional.](http://mislav.uniqpath.com/2010/05/semicolons/) – Derek 朕會功夫 Apr 10 '12 at 02:10
  • Why don't you actually try to solve my problem instead of criticizing my errors which obviously have nothing to do with my problem – James Fair Apr 10 '12 at 02:10
  • 1
    Also the regex for email checking `^\w*@\w*.com` could definitely be improved. That rejects `someone@telus.net` and `someone@shaw.ca`, but it allows `@.com!@#$%` and `@_.comfoobar` to pass as valid. – Paul Apr 10 '12 at 02:11
  • @JamesFair Do you only want to fix one problem, or many? Neuroburn already pointed out what prevents your regex from working after the first click below, but you have many other problems with your code that will turn into errors later. You should appreciate the advice and make the changes now rather then when they are causing bugs you don't even know about. – Paul Apr 10 '12 at 02:13
  • @PaulP.R.O Thanks for the advice, but I just made those regular expressions of the fly, I was not going to use them in production without making them more robust! – James Fair Apr 10 '12 at 02:16
  • @am not i am Sorry, I will surely do that next time, thanks – James Fair Apr 10 '12 at 02:22
  • @JamesFair, Your regex for checking email is not accurate. For a more accurate one, please use [RFC822](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html) :P. – Derek 朕會功夫 Apr 10 '12 at 03:39

1 Answers1

5

"As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match." https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/test

You can work around this behavior by either resetting the lastIndex to 0 or creating a new regex each test.

ɲeuroburɳ
  • 6,990
  • 3
  • 24
  • 22