$.validator.addMethod('requiredif', (value, element) => { const otherFieldValue = element.getAttribute('data-val-requiredif-value'); // optional const otherFieldName = element.getAttribute('data-val-requiredif-other'); const otherFieldElement = element.form[otherFieldName]; if (otherFieldValue) { if (otherFieldElement.value === otherFieldValue) { // the other field matches the value, so this field is required, and // thus valid only if a value is given return Boolean(value); } // the other field does not match the value, so this element is not // required, and thus always valid return true; } else { // compare if its a checked checkbox or an input with something in it if ((otherFieldElement.type === 'checkbox' && otherFieldElement.checked) || (otherFieldElement.type !== 'checkbox' && otherFieldElement.value)) { // the other field is checked or provided, so this field is required, and // thus valid only if it has a value return Boolean(value); } // the other field does not match the value, so this element is not // required, and thus always valid return true; } });