私はPayment.jsプラグインを使用してクレジットカードの入力フィールドをフォーマットして検証しています。私はkeyup/focusoutでクライアント側を検証する必要があります。また、サーバーのサブミット後にエラーメッセージが返されます。エラー・スタイリングは、無効なフィールドに固有のものにしたい。私のコードは私が望むように動作していますが、より効率的に/簡潔にしたいと思います。どんなアドバイスも大歓迎です!もっと簡潔なjQuery if/else for input validation
1)やる$toggleErrorStyling
機能にそうdo(cond)
パターン
でif (cond) do(true) else do(false)
パターンを置き換えます:ここで
$(function() {
// Initiate payment.js plugin
$('.cc-num').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
// Toggle error styling
$toggleErrorStyling = function(el, erred) {
var inputContainer = $(el).parents('.input-container');
if (erred) {
inputContainer.addClass('has-error').removeClass('has-success');
} else {
inputContainer.removeClass('has-error').addClass('has-success');
}
};
// Validate each form field
$('.paymentInput').bind('focusout', function() {
var valid,
erred = function(valid) {},
$hdnCCType = $('input[id$="hdnCCType"]'),
$cardType = $.payment.cardType($('.cc-num').val()),
$errorMsg = $('.alert-danger');
if ($(this).hasClass('cc-num')) {
valid = $.payment.validateCardNumber($(this).val());
if (valid) {
$hdnCCType.val($cardType); // set the hidden value to post back to the Server
}
} else if ($(this).hasClass('cc-exp')) {
// validate expiry date
valid = $.payment.validateCardExpiry($('.cc-exp').payment('cardExpiryVal'));
} else if ($(this).hasClass('cc-cvc')) {
//validate security code
valid = $.payment.validateCardCVC($('.cc-cvc').val(), $cardType);
}
$errorMsg.hide();
erred(valid);
$toggleErrorStyling(this, !valid);
});
// After form submit,
// if .alert-danger is visible on the page,
// validate all three inputs,
// but return error styling only on the invalid ones,
// and ignore hash marks on browser back from verify ?edit=T
if ($(".alert-danger").is(":visible")) {
var $cardType = $.payment.cardType($('.cc-num').val());
if (!$.payment.validateCardNumber($('.cc-num').val())) {
$toggleErrorStyling($('.cc-num'), true);
} else {
$toggleErrorStyling($('.cc-num'), false);
}
if (!$.payment.validateCardExpiry($('.cc-exp').payment('cardExpiryVal'))) {
$toggleErrorStyling($('.cc-exp'), true);
} else {
$toggleErrorStyling($('.cc-exp'), false);
}
if (!$.payment.validateCardCVC($('.cc-cvc').val(), $cardType)) {
$toggleErrorStyling($('.cc-cvc'), true);
} else {
$toggleErrorStyling($('.cc-cvc'), false);
}
}
});
投稿したコードは無効です:開こうとしている括弧がもう1つあります。そしてそれをどのように解釈するのかは明らかではありません。 – trincot
ありがとうございます。私はCTRL + Kショートカットで何かが間違っていると思う。私は再フォーマットしました。 – Razzle
この質問は、(a)あなたのコードが意図したとおりに機能し、(b)あなたのコードがサンプルコードではなく実際のコードである限り、[コードレビュー](http://codereview.stackexchange.com/help) (c)あなたのコードは質問の本文に含まれています。ピアレビューでコードのすべての面を改善したい場合は、Code Reviewに投稿してください。 –