Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Client-side validation for donation pages. Empty required fields are highlighted and the donor is advised to fill them in.
<!-- Add client-side validation to donation pages. -->
<style>
/* Empty required fields are given these styles. */
select.errorInput,
input.errorInput,
fieldset.errorInput {
border: 3px solid red;
}
.salsa form .error {
background: none;
border: none;
color: red;
font-size: 1.2em;
margin-bottom: 20px;
width: 100%;
}
</style>
<script type="text/javascript">
/* Function to validate required fields in a Salsa form. Empty required
* fields are decorated with the CSS declarations (above).
* @note This function overrides the
* @param Object form DOM element for the form, typically document.forms[0]
*/
function submitForm(form) {
var req = s$(form).find("input[name='required']").val();
req = req.concat('cc_type,cc,ccExpMonth,ccExpYear,CVV2'.split(','));
if (req) {
var hasRequired = true;
req = req.split(",");
for (var i = 0; i < req.length; i++) {
if (!req[i]) continue;
var field = s$(form).find("select[name='" + req[i] + "'],input[name='" + req[i] + "']");
//if there is no such field, continue on
if (field.length == 0) continue;
var val = field.val();
if (val == null || val.length == 0) {
hasRequired = false;
field.addClass("errorInput");
} else {
field.removeClass("errorInput");
}
}
}
if ($('*[id^=amt]:checked', ".salsa form").length == 0 && $('#otheramt').val().trim().length == 0) {
$('#donation_amount').addClass('errorInput');
hasRequired = false;
} else {
$('#donation_amount').removeClass('errorInput');
}
if (hasRequired == false) {
if (s$('#errorMessage').length == 0) {
s$('form').append('<div class="formRow"><div class="error" id="errorMessage"></div></div');
}
s$("#errorMessage").html("<span class='error'>Please fill out all required fields</span>");
}
return hasRequired;
}
// Enable client-side validation if there's a donate_page_KEY. That will allow this
// script to also run on donation pages with a Salsa shortcut.
s$(document).ready(function () {
if (s$('input[name="donate_page_KEY"]').length != 0) {
s$('.salsa form').submit(function () { return submitForm(this); })
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.