0

I've got some jQuery in an ascx file (Sharepoint WebPart) that responds to a checkbox's changed event, manipulating properties of another control/element based on the state of the checkbox (checked or unchecked, that is the question):

$(document).on("change", '[id$=ckbxEmp]', function () {       
    var ckd = this.checked;
    var $input = $('[id$=txtbxSSNOrITIN]');
    if(ckd) $input.data("oldValue", $input.val()); // Remember current value    
    $input.prop("maxlength", ckd? 4 : 12).css({
        background: ckd? 'yellow' : "lightgreen",
        width: ckd? 40 : 80
    }).val(function(i, v){
        // If checked, slice value to four chars:
        return ckd && v.length>4 ? v.slice(0,4) : $input.data("oldValue");
    });    
}); 

The script above can be run from this fiddle, which is based on an answer I got here

What I yet need to add is custom validation code. If in Employee (SSN) mode (the checkbox is checked), I guess I just need to verify that four chars in the 0..9 subset were entered; if ITIN, though (the checkbox is unchecked), I need a more complicated validation. How do I incorporate that? Do I need to write validation functions and call them from the "val" function? IOW, should this line:

return ckd && v.length>4 ? v.slice(0,4) : $input.data("oldValue");

...be changed to something like:

return ckd && v.length>4 ? getSSN($input.data) : getITIN($input.data);

...and then code up functions like so:

function getSSN(var entry) {
    // validate/verify, slice to 4 chars if necessary
}

function getITIN(var entry) {
    // validate/verify, slice to 12 if necessary
}

...or what?

UPDATE

Come to think of it, it seems logical (in fact, downright obvious) that I need to create an event handler for the textbox, something like (pseudoscript):

$(document).on("change", '[id$=txtbxSSNOrITIN]', function () {       
    var $input = $('[id$=txtbxSSNOrITIN]');
    var ckbxChecked = "#ckbxEmp".checked;
    if (ckbxChecked) {
        // validate for SSN, passing $input
    }
    else {
        // validate for ITIN, passing $input
    }
});

But "how do I get there from here" is the question...

Community
  • 1
  • 1
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Use regex for complex string validation, if it is your question?! https://regex101.com/#javascript – A. Wolff Jun 03 '15 at 18:16
  • I may go down the garden path that is RegEx (it makes my hair stand on end to think about it, and gives me the fantods to look at it) if need be, but my question is more: "How can I validate an entry from within an event handler?" – B. Clay Shannon-B. Crow Raven Jun 03 '15 at 18:25

0 Answers0