Jay Jay - 3 months ago 17
jQuery Question

Adding client side validation failures to ASP.NET MVC ModelState

Within a HTTP post page I have the following DIV specified:

<div class="centered" style="text-align:center">
<span class="help-block">
@Html.ValidationSummary(true)
</span>
</div>


I have the following javascript validation:

function validate() {

var cardTypeCheck = RealexRemote.validateCardType(document.getElementById('cardType').value);
var cardNumberCheck = RealexRemote.validateCardNumber(document.getElementById('cardNumber').value);
var cardHolderNameCheck = RealexRemote.validateCardHolderName(document.getElementById('cardholderName').value);
var expiryDateMonthCheck = RealexRemote.validateExpiryMonthDateFormat(document.getElementById('expiryDateMM').value);
var expiryDateYearCheck = RealexRemote.validateExpiryYearDateFormat(document.getElementById('expiryDateYY').value);
var expiryDateFormatCheck = RealexRemote.validateExpiryDateFormat(document.getElementById('expiryDateMM').value.concat(document.getElementById('expiryDateYY').value));
var expiryDatePastCheck = RealexRemote.validateExpiryDateNotInPast(document.getElementById('expiryDateMM').value.concat(document.getElementById('expiryDateYY').value));
if (document.getElementById('cardNumber').value.charAt(0) == "3") { cvnCheck = RealexRemote.validateAmexCvn(document.getElementById('cvn').value); }
else { cvnCheck = RealexRemote.validateCvn(document.getElementById('cvn').value); }
if (cardNumberCheck == false || cardHolderNameCheck == false || expiryDateYearCheck == false || expiryDateYearCheck == false || expiryDateFormatCheck == false || expiryDatePastCheck == false || cvnCheck == false) {
// code here to inform the cardholder of an input error and prevent the form submitting
if (cardTypeCheck == false) { alert("Card Type must be selected") }
if (cardNumberCheck == false) { alert("Card Number entered is not valid") }
if (expiryDateMonthCheck == false) { alert("Expiry Date Month must be selected") }
if (expiryDateYearCheck == false) { alert("Expiry Date Year must be selected") }
if (expiryDateMonthCheck == true && expiryDateYearCheck == true)
{
if (expiryDatePastCheck == false) { alert("Expiry Date must not be in the past") }
}
if (cardHolderNameCheck == false) { alert("Card Holder name must be entered") }
if (cvnCheck == false) { }
return false;
}
else
return true;
}


Instead of putting out validation errors as javascript alerts I would like to add them to the ModelState Errors lists but I am unsure of how to do this when on the client side. I have attempted:

if (cvnCheck == false) {
var ul = $(".help-block ul");
ul.append("<li>Security Code must be entered</li>")
}


But this is not displaying, how can I set my ModelState to be invalid on the client side

Jay Jay
Answer
var helpBlock = $(".help-block"); helpBlock.append("<div class=\"validation-summary-errors\"></div>");
$(".validation-summary-errors").append("<li>" + "Expiry Date Year must be selected" + "</li>");