Search code examples
javascriptbackbone.js

How to disallow special characters in PAN number using BackboneJS


I am trying to add a PAN number validation to disallow special chars, but my code as follows is not working as expected:

if (attributes.isOwnProfile &&
    attributes.totalExperience > 0 &&
    $.trim(attributes.panNumber) == "") {
    errors.push({
        key: "panNo",
        message: "Required"
    });
} else if ($.trim(attributes.panNumber) != "" &&
    attributes.panNumber.length !== 10) {
    errors.push({
        key: "panNo",
        message: "Not a valid PAN No"
    });
} else if (!(/[^a-zA-Z0-9]/).test(attributes.panNumber)) {
    errors.push({
        key: "panNo",
        message: "Not a valid PAN No"
    });
}

Solution

  • Your regex is checking whether any special character is present or not, if present it returns true, which you're negating with the ! operator, so the condition is not met when special characters are present.

    You should remove the ! from the if condition

    else if((/[^a-zA-Z0-9]/).test(attributes.panNumber)) {
       errors.push({
          key: "panNo",
          message: "Not a valid PAN No"
          });
    }