Search code examples
javascriptjqueryregexjquery-validatemask

Jquery Validation with SSN Regex, Masked Input and Depends


I'm having trouble getting the Jquery Validation to work with the following rules.

I have the field masked with SSN format, the validation must not allow submission of this information without it being a complete SSN. I have a working regex function that rejects non SSNs. I need it to not allow blank submissions as well (the mask is only applied if the field is onFocus). And last but not least, the field is NOT required if another checkbox is checked (#noSSN).

I've added a JSfiddle page to help: http://jsfiddle.net/B2UpW/3/

It appears to be working a bit different on the fiddle page. Hope this helps!

Edit: I've yet to receive any responses.. curious if there is any confusion about my question? Any suggestions to help find some assistance is welcome!

$("#ssn").mask("999-99-9999");

$.validator.addMethod("notEqual", function(value, element, param) {
  return this.optional(element) || value !== param;
}, "Please choose a value!");           

$("#applicantForm").validate({
    rules: {        
        ssn: {
            notEqual: "___-__-____", 
            required: {
                depends: function(element) {
                    return ($("#ssn").val() == ""
                            || isValidSSN($("#ssn").val()) 
                            || $("#noSSN:unchecked"));
                }                   
            }                   

        }
    },
    messages: {
        ssn: 'Please enter a social security number.'
    }
});


function isValidSSN(value) { 
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/; 
    if (!re.test(value)) { return false; } 
    var temp = value; 
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); } 
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); } 
    if (temp.substring(0, 3) == "000") { return false; } 
    if (temp.substring(3, 5) == "00") { return false; } 
    if (temp.substring(5, 9) == "0000") { return false; } 
    return true; 
}

Solution

  • You just needed to add a check to see if the checkbox was, er, checked.

    See this updated fiddle, around line 9 (or line 2 in the code below) where you check if the SSN is valid:

    $('#submitApplication').live('click', function() {
        if ($('#noneSSN').is(':checked'))
        {
            alert("SUCCESS");
        }
        else
        {
            var isValid = $("#applicantForm").valid();
            if (isValid) {
                alert("SUCCESS");
            }
        }
        return false;
    });
    

    It will now allow a submit if the box is checked, otherwise it will demand a correct SSN.