Advertisement
patrickt

Rocking out with jQuery validate with dynamic rules

Jan 6th, 2014
746
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Reference: http://jqueryvalidation.org/rules
  3.  */
  4. $(document).ready(function() {
  5.     var rules = {
  6.         IncomeSource: 'required',
  7.         NetIncome: {
  8.             required: true,
  9.             usDollar: true,
  10.             minDollars: 1
  11.         },
  12.         //Begin - Fields that don't always show
  13.         JobTitle: {
  14.             //required: true,
  15.             nameInput: true
  16.         },
  17.         Employer: {
  18.             //required: true,
  19.             nameInput: true
  20.         },
  21.         EmployerPhone: {
  22.             //required: true,
  23.             phoneUS: true
  24.         },
  25.         BenefitSource: {
  26.             //required: true,
  27.             nameInput: true
  28.         },
  29.         //SemiMonthlySpecifics: 'required', //Select one when Semi-Monthly or Monthly are selected
  30.         //End - Fields that don't always show
  31.         PayFrequency: 'required',
  32.         LastPayDate: {
  33.             required: true,
  34.             pastDate: true,
  35.             date: true
  36.         },
  37.         NextPayDate: {
  38.             required: true,
  39.             futureDate: true,
  40.             date: true
  41.         },
  42.         DirectDeposit: 'required',
  43.         EmploymentLength: 'required',
  44.         ActiveMilitary: 'required',
  45.         RoutingNumber: {
  46.             required: true,
  47.             digits: true,
  48.             rangelength: [9, 9]
  49.         },
  50.         AccountNumber: {
  51.             required: true,
  52.             digits: true,
  53.             rangelength: [4, 17]
  54.         },
  55.         AccountType: 'required'
  56.     };
  57.  
  58.     //And field specific (and even validation type specific) error messages
  59.     var messages = {
  60.         IncomeSource: ss.i18n._t('IncomeSourceRequiredError'),
  61.         NetIncome: {
  62.             required: ss.i18n._t('NetIncomeRequiredError')
  63.         },
  64.         //Begin - Fields that don't always show
  65.         JobTitle: {
  66.             required: ss.i18n._t('JobTitleRequiredError')
  67.         },
  68.         Employer: {
  69.             required: ss.i18n._t('EmployerRequiredError')
  70.         },
  71.         EmployerPhone: {
  72.             required: ss.i18n._t('EmployerPhoneRequiredError')
  73.         },
  74.         BenefitSource: {
  75.             required: ss.i18n._t('BenefitSourceRequiredError')
  76.         },
  77.         SemiMonthlySpecifics: ss.i18n._t('SemiMonthlySpecificsRequiredError'), //Select one when Semi-Monthly or Monthly are selected
  78.         //End - Fields that don't always show
  79.         PayFrequency: ss.i18n._t('PayFrequencyRequiredError'),
  80.         LastPayDate: {
  81.             required: ss.i18n._t('LastPayDateRequiredError')
  82.         },
  83.         NextPayDate: {
  84.             required: ss.i18n._t('NextPayDateRequiredError')
  85.         },
  86.         DirectDeposit: ss.i18n._t('DirectDepositRequiredError'),
  87.         EmploymentLength: ss.i18n._t('EmploymentLengthRequiredError'),
  88.         ActiveMilitary: ss.i18n._t('ActiveMilitaryRequiredError'),
  89.         RoutingNumber: {
  90.             required: ss.i18n._t('RoutingNumberRequiredError')
  91.         },
  92.         AccountNumber: {
  93.             required: ss.i18n._t('AccountNumberRequiredError')
  94.         },
  95.         AccountType: ss.i18n._t('AccountTypeRequiredError')
  96.     };
  97.  
  98.     $('#applicationForm').validate({
  99.         //debug: true,
  100.         rules: rules,
  101.         messages: messages,
  102.         errorElement: 'span',
  103.         ignore: '.ignore',
  104.         onfocusout: function( element, event ) {
  105.             $(element).valid();
  106.         },
  107.         invalidHandler: function(event, validator) {
  108.             kclHelpers.openErrorModal(event, validator);
  109.         },
  110.         errorPlacement: function(error, element) {
  111.             var insertLocation = kclHelpers.getInsertLocation(element);
  112.             error.appendTo( insertLocation );
  113.         },
  114.         success: function(label, element) {
  115.             element = $(element);
  116.             var insertLocation = kclHelpers.getInsertLocation(element);
  117.             insertLocation.hide();
  118.             kclHelpers.parentShowSuccess(element, '.control-group');
  119.         },
  120.         //Had to use this for show/hide of errors because error placement doesn't get called on every error.
  121.         showErrors: function(errorMap, errorList) {
  122.             if (this.numberOfInvalids() > 0) {
  123.                 //We want to make sure that we show/hide things appropriately on error
  124.                 $.each(errorList, function(index, item) {
  125.                     var domElement = item['element'];
  126.                     var message = item['message'];
  127.  
  128.                     var element = $(domElement);
  129.                     var insertLocation = kclHelpers.getInsertLocation(element);
  130.                     insertLocation.show();
  131.                     kclHelpers.parentShowError(element, '.control-group');
  132.                 });
  133.             }
  134.  
  135.             this.defaultShowErrors();
  136.         }
  137.     });
  138.  
  139.     $('[rel=tooltip]').tooltip();
  140.  
  141.     // When the income source is changed, change the form respectively
  142.     $('#IncomeSource').on('change', kclFinancialInfo.incomeSourceChanged);
  143.     $('#PayFrequency').on('change', kclFinancialInfo.payFrequencyChanged);
  144. });
  145.  
  146.  
  147.  
  148. /**
  149.  * This is where we specify functions only for this form
  150.  */
  151. var kclFinancialInfo = function()
  152. {
  153.     return {
  154.         incomeSourceChanged: function() {
  155.             // Store and convert the income source to lowercase
  156.             var val = $(this).val().toLocaleLowerCase();
  157.  
  158.             // Switch on the income source
  159.             switch (val) {
  160.                 // Case for 'benefits'
  161.                 case 'benefits':
  162.                     // Do not display the employment section
  163.                     kclFinancialInfo.toggleEmploymentSection(false);
  164.  
  165.                     // Display the benefit source section
  166.                     kclFinancialInfo.toggleBenefitSource(true);
  167.                     break;
  168.  
  169.                 // Case for 'selfemployment'
  170.                 case 'selfemployment':
  171.                     // Display the benefit source section
  172.                     kclFinancialInfo.toggleBenefitSource(false);
  173.  
  174.                     // Display the employment section
  175.                     kclFinancialInfo.toggleEmploymentSection(true, "Please enter your company's name");
  176.  
  177.                     // Call to update the labels for the employment section based on income source of 'selfemployment'
  178.                     kclFinancialInfo.updateEmploymentSectionLabels('selfemployment');
  179.  
  180.                     // Hide the employer phone field
  181.                     kclFinancialInfo.toggleEmployerPhone(true);
  182.                     break;
  183.  
  184.                 // Case for 'job' and default
  185.                 case 'job':
  186.                 default:
  187.                     // Do not display the benefit source
  188.                     kclFinancialInfo.toggleBenefitSource(false);
  189.  
  190.                     // Display the employment section
  191.                     kclFinancialInfo.toggleEmploymentSection(true, "Please enter your employer's name");
  192.  
  193.                     // Call to update the labels for the employment section based on income source of 'job'
  194.                     kclFinancialInfo.updateEmploymentSectionLabels('job');
  195.  
  196.                     // Do not hide the employer phone field
  197.                     kclFinancialInfo.toggleEmployerPhone(false);
  198.                     break;
  199.             }
  200.         },
  201.  
  202.         payFrequencyChanged: function() {
  203.             var val = $(this).val().toLocaleLowerCase();
  204.  
  205.             switch (val) {
  206.                 case 'semi_monthly':
  207.                     // Display the Specific SemiMonthly section
  208.                     kclFinancialInfo.toggleSpecificSemiMonthly(true, val);
  209.  
  210.                 case 'monthly':
  211.                     // Display the Specific SemiMonthly section BUT change the labels
  212.                     kclFinancialInfo.toggleSpecificSemiMonthly(true, val);
  213.  
  214.                     break;
  215.                 default:
  216.                     // Do not display the Specific SemiMonthly section
  217.                     kclFinancialInfo.toggleSpecificSemiMonthly(false);
  218.                     break;
  219.             }
  220.         },
  221.  
  222.         toggleSpecificSemiMonthly: function(show, value) {
  223.             if (show) {
  224.                 if (value == 'semimonthly') {
  225.                     $('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SEMI_MONTHLY_SPECIFICS_DAY'));
  226.                     $('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SEMI_MONTHLY_SPECIFICS_DATE'));
  227.                 }
  228.                 else {
  229.                     $('#specifics-label-for-SemiMonthlySpecifics_day').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.MONTHLY_SPECIFICS_DAY'));
  230.                     $('#specifics-label-for-SemiMonthlySpecifics_date').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.MONTHLY_SPECIFICS_DATE'));
  231.                 }
  232.  
  233.                 $('#semi-monthly-specifics').show().removeClass('hidden');
  234.                 $('input[name="SemiMonthlySpecifics"]').rules('add', 'required');
  235.             }
  236.             else {
  237.                 kclHelpers.hideMessage('SemiMonthlySpecifics');
  238.                 $('#semi-monthly-specifics').hide().addClass('hidden');
  239.                 $('input[name="SemiMonthlySpecifics"]').rules('remove', 'required');
  240.             }
  241.         },
  242.  
  243.         toggleEmployerPhone: function(hide) {
  244.             // If you want to hide the employer phone field
  245.             if (hide) {
  246.                 // Hide the employer phone
  247.                 $('#employer_phone').hide().addClass('hidden');
  248.                 $('employer_phone').rules('remove', 'required');
  249.             }
  250.             // Else (you don't want to hide the employer phone field)
  251.             else {
  252.                 // Display the employer phone field
  253.                 $('#employer_phone').show().removeClass('hidden');
  254.                 $('employer_phone').rules('add', 'required');
  255.             }
  256.         },
  257.  
  258.         toggleBenefitSource: function(show) {
  259.             // If you want to show the benefit sources section
  260.             if (show) {
  261.                 // Show the benefit source section
  262.                 $('#benefit_source').show().removeClass('hidden');
  263.  
  264.                 // Since the benefit source section is now visible, make it required
  265.                 $('#BenefitSource').rules('add', 'required');
  266.  
  267.                 /**
  268.                  * Hide the WorkPhone validation message if its displayed (it remains on the screen if the user
  269.                  * selects benefits)
  270.                  */
  271.                 kclHelpers.hideMessage('WorkPhone');
  272.             }
  273.             // Else (you don't want to show the benefit source section, display the default employment section)
  274.             else {
  275.                 // Hide the benefit source section
  276.                 $('#benefit_source').hide().addClass('hidden');
  277.  
  278.                 // Since the benefit source is now hidden, it is no longer required
  279.                 $('#BenefitSource').rules('remove', 'required');
  280.             }
  281.         },
  282.  
  283.         toggleEmploymentSection: function(show, employerMessage = '') {
  284.             // If you want to show the employment section
  285.             if (show) {
  286.                 // Show the employment section
  287.                 $('#employment_section').show();
  288.                 $('#JobTitle').rules('add', 'required');
  289.                 $('#Employer').rules('add', {
  290.                     required: true,
  291.                     messages: {
  292.                         required: employerMessage
  293.                     }
  294.                 });
  295.                 $('#EmployerPhone').rules('add', 'required');
  296.             }
  297.             // Else (you don't want to show the employment section)
  298.             else {
  299.                 // Hide the employment section
  300.                 $('#employment_section').hide();
  301.                 $('#JobTitle').rules('remove', 'required');
  302.                 $('#Employer').rules('remove', 'required');
  303.                 $('#EmployerPhone').rules('remove', 'required');
  304.             }
  305.         },
  306.  
  307.         updateEmploymentSectionLabels: function(source) {
  308.             // Switch on the income source (now lowercase)
  309.             switch (source.toLocaleLowerCase()) {
  310.                 // Case for 'job'
  311.                 case 'job':
  312.                     /**
  313.                      * Make sure the job title and employer labels are correct (this is needed in case the labels
  314.                      * need to be changed back to default
  315.                      */
  316.                     $('#JobTitle_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.JOB_TITLE'));
  317.                     $('#Employer_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.EMPLOYER'));
  318.                     $('#Employer').attr('placeholder', 'Enter Employer Name');
  319.  
  320.                     break;
  321.                 // Case for 'selfemployment'
  322.                 case 'selfemployment':
  323.                     // Change the employer label to correspond to self employment (Employer -> Your Company Name)
  324.                     $('#Employer_label').text(ss.i18n._t('FINANCIAL_INFORMATION_PAGE.SELF_EMPLOYER'));
  325.                     $('#Employer').attr('placeholder', 'Enter Company Name');
  326.                     break;
  327.             }
  328.         }
  329.     }
  330. }();
  331.  
  332.  
  333. var kclHelpers = function()
  334. {
  335.     var firstErrorID = '';
  336.     var errorCount = 0;
  337.  
  338.     return {
  339.         //Expects jQuery element
  340.         getInsertLocation: function(element) {
  341.             var fieldName = element.attr('name');
  342.  
  343.             if (fieldName == 'Reference_1[Relationship]') {
  344.                 fieldName = 'Reference_1-Relationship';
  345.             }
  346.             else if (fieldName == 'Reference_2[Relationship]') {
  347.                 fieldName = 'Reference_2-Relationship';
  348.             }
  349.  
  350.             var insertTo = "#" + fieldName + "-error";
  351.             return $(insertTo);
  352.         },
  353.  
  354.         //Expects jQuery element and a selector string
  355.         parentShowError: function(element, parentSelector) {
  356.             var parentElem = element.parents(parentSelector);
  357.  
  358.             if (!parentElem.hasClass('has-error')) {
  359.                 parentElem.addClass('has-error');
  360.             }
  361.  
  362.             parentElem.removeClass('has-success');
  363.         },
  364.  
  365.         //Expects jQuery element and a selector string
  366.         parentShowSuccess: function(element, parentSelector) {
  367.             var parentElem = element.parents(parentSelector);
  368.  
  369.             if (!parentElem.hasClass('has-success')) {
  370.                 parentElem.addClass('has-success');
  371.             }
  372.  
  373.             parentElem.removeClass('has-error');
  374.         },
  375.  
  376.         hideMessage: function(fieldName) {
  377.             if (fieldName == 'CreatePassword') {
  378.                 // Clear the Create-Password error message as well as the Confirm-Password error message
  379.                 $('#ConfirmPassword-error').hide();
  380.             }
  381.  
  382.             if (fieldName == 'CellPhone') {
  383.                 // Clear the Cell-Phone error message as well as the Home-Phone error message
  384.                 $('#HomePhone-error').hide();
  385.             }
  386.  
  387.             /**
  388.              * Find the id in the form styling file corresponding to field we wish to "clear"
  389.              * And set its "display" value to "none", effectively deleting it
  390.              * This is for the desktop version
  391.              */
  392.             $("#" + fieldName + "-error").hide();
  393.         },
  394.  
  395.         openErrorModal: function(event, validator) {
  396.             var errorCnt = validator.numberOfInvalids();
  397.             var errors = '';
  398.             var hasSetErrorID = false;
  399.             kclHelpers.errorCount = errorCnt;
  400.  
  401.             if (errorCnt) {
  402.                 var message = "";
  403.  
  404.                 for (var i in validator.errorMap) {
  405.                     if (!hasSetErrorID) {
  406.                         hasSetErrorID = true;
  407.                         kclHelpers.firstErrorID = i;
  408.                     }
  409.  
  410.                     var str = i;
  411.                     var label = '';
  412.  
  413.                     if (i == 'AgreeTerms') {
  414.                         label = 'Website terms';
  415.                     }
  416.                     else if (i == 'ContactTerms') {
  417.                         label = 'Contact terms';
  418.                     }
  419.                     else if (i == 'HomePhone') {
  420.                         label = 'Home Phone';
  421.                     }
  422.                     else if (i == 'RoutingNumber') {
  423.                         label = 'Routing Number';
  424.                     }
  425.                     else if (i == 'AccountNumber') {
  426.                         label = 'Account Number';
  427.                     }
  428.                     else if (i == 'SemiMonthlySpecifics') {
  429.                         label = 'Pay Frequency Specifics';
  430.                     }
  431.                     else if (/Reference_1/i.test(str)) {
  432.                         label = 'Reference 1 ' + $("label[for='" + i + "']").text();
  433.                     }
  434.                     else if (/Reference_2/i.test(str)) {
  435.                         label = 'Reference 2 ' + $("label[for='" + i + "']").text();
  436.                     }
  437.                     else {
  438.                         label = $("label[for='" + i + "']").text();
  439.                     }
  440.  
  441.                     errors += '<li>' + label + ': ' + validator.errorMap[i] + '</li>';
  442.                 }
  443.  
  444.                 message += '<ol>' + errors + '</ol>';
  445.  
  446.                 $('#form-error-modal .modal-body .error-count').text(errorCnt);
  447.                 $('#form-error-modal ul.error-list').html(message);
  448.                 $('#form-error-modal').modal('show');
  449.             }
  450.         }
  451.     }
  452. }();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement