1

I've been looking at the jQuery Validation Plugin and it seems like overkill (my site's script requirements are ballooning), and also not quite what I want.

Let me define some terminology: an <input type="text"> field's status is VALID if it matches both RegEx 1 and RegEx 2, PARTIAL if it matches RegEx 1 but not RegEx 2, and INVALID if it doesn't match RegEx 1.

For example, RegEx 1 could be /^[A-Z_]*$/ and RegEx 2 could be /^[A-Z]+(_[A-Z]+)*$/.

The requirements are:

  • any key press which would lead to an INVALID status is ignored, without interfering with focus or the caret position, and without the value ever being seen to change,
  • otherwise the status is updated after every key press to be either VALID or PARTIAL, and
  • whenever an input's status changes, a callback is invoked.

Seems pretty straightforward. This is basically the QStringValidator model.

I have jQuery core but I'm new to it. How can I implement this? Thanks.

P.S. if the best solution lies outside of jQuery, IE support is not required.

spraff
  • 32,570
  • 22
  • 121
  • 229

1 Answers1

0
if (this.value.match(this.getAttribute('data-regex1')) {
    if (this.value.match(this.getAttribute('data-regex2')) {
        do_whatever_for_full();
    } else {
        do_whatever_for_partial();
    }
} else {
    do_whatever_for_invalid();
}

Put your regexes into the element as custom attributes (data-regex1, data-regex2) then check the data as it changes (not sure how many events you want to check but you probably have to check with onkeydown ignoring enter and tab, or you could create a timer onfocus and just check every half second or so).

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
Magic Lasso
  • 1,504
  • 5
  • 22
  • 29
  • I'm afraid the bit you glossed over -- the events -- is *exactly* what the question is about. – spraff Jan 08 '14 at 19:39
  • This thread has the events you are looking for: http://stackoverflow.com/questions/574941/best-way-to-track-onchange-as-you-type-in-input-type-text – Magic Lasso Jan 08 '14 at 19:56
  • you can create an array with each of the inputs you want to test and use input_element.addEventListener('keydown',function(){function_name.call(input_element);},false); – Magic Lasso Jan 08 '14 at 19:58
  • scratch that one updated to ignore enter key presses: http://jsfiddle.net/9hhAT/2/ – Magic Lasso Jan 08 '14 at 20:18