Example usage for org.apache.commons.validator.routines CreditCardValidator isValid

List of usage examples for org.apache.commons.validator.routines CreditCardValidator isValid

Introduction

In this page you can find the example usage for org.apache.commons.validator.routines CreditCardValidator isValid.

Prototype

public boolean isValid(String card) 

Source Link

Document

Checks if the field is a valid credit card number.

Usage

From source file:facturas.Window2.java

private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCheckActionPerformed
    //Realizamos la comprobacion de si existe o no la tarjeta de credito
    CreditCardValidator ccValidator = new CreditCardValidator();
    boolean cardValid = ccValidator.isValid(jTextFieldCode.getText());
    String mensaje = cardValid ? "Tarjeta vlida" : "Tarjeta no vlida";
    JOptionPane.showMessageDialog(this, mensaje);
}

From source file:Ventana.java

private void jButtonComprobarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonComprobarActionPerformed

    // Inicializamos los JText Validadores
    jTextValidTarjeta.setText("");
    jTextValidISBN.setText("");
    jTextValidEmail.setText("");

    // Validamos la Tarjeta de Credito
    if (!jTextNumTarjeta.getText().equals("")) {

        CreditCardValidator validaTarjeta = new CreditCardValidator();

        if (validaTarjeta.isValid(jTextNumTarjeta.getText()))
            jTextValidTarjeta.setText("Correcto");
        else//from ww  w  . ja v a2s  . co  m
            jTextValidTarjeta.setText("Incorrecto");
    }

    // Validamos el ISBN
    if (!jTextISBN.getText().equals("")) {

        ISBNValidator validaISBN = new ISBNValidator();

        if (validaISBN.isValid(jTextISBN.getText()))
            jTextValidISBN.setText("Correcto");
        else
            jTextValidISBN.setText("Incorrecto");
    }

    // Validamos el Email
    if (!jTextEmail.getText().equals("")) {

        EmailValidator validaEmail = EmailValidator.getInstance();

        if (validaEmail.isValid(jTextEmail.getText()))
            jTextValidEmail.setText("Correcto");
        else
            jTextValidEmail.setText("Incorrecto");
    }

}

From source file:com.threew.validacion.tarjetas.credito.utilidad.Validador.java

/***
 * Valida a partir de la propiedad nmero de tarjeta 
 * * @return boolean/*ww  w .ja  v a2  s  . c  o  m*/
 **/
public boolean validar() {
    if (prevalidarTarjeta(this.numeroTarjetaString) == Boolean.FALSE) {
        return Boolean.FALSE;
    }
    /// Crear instancia de validador de Apache
    CreditCardValidator validador = new CreditCardValidator(
            CreditCardValidator.AMEX + CreditCardValidator.VISA + CreditCardValidator.MASTERCARD);

    /// Procesar y retornar
    return validador.isValid(this.numeroTarjetaString);
}

From source file:com.threew.validacion.tarjetas.credito.utilidad.Validador.java

/***
 * Valida a partir de la propiedad nmero de tarjeta 
 * @param numero Es el numero de tarjeta en formato string.
 * @return boolean// ww w.j av a  2  s.  com
 **/
public boolean validar(String numero) {
    if (prevalidarTarjeta(numero) == Boolean.FALSE) {
        return Boolean.FALSE;
    }
    /// Crear instancia de validador de Apache
    CreditCardValidator validador = new CreditCardValidator(
            CreditCardValidator.AMEX + CreditCardValidator.VISA + CreditCardValidator.MASTERCARD);

    /// Procesar y retornar
    return validador.isValid(numero);
}

From source file:com.mastercard.masterpasswallet.fragments.addcard.VerifyCardFragment.java

private void setupAddCardButton(View fragmentView) {
    Button btnAddCard = (Button) fragmentView.findViewById(R.id.btn_add_card);
    btnAddCard.setOnClickListener(new View.OnClickListener() {
        @Override/*  w  w  w. j  a va 2s  . co  m*/
        public void onClick(View view) {
            Log.d(TAG, "Card added button pressed");
            String cardholderName = mEdtCardholderName.getText().toString();
            String cardNumber = mEdtCardNumber.getText().toString();
            String cvc = mEdtCvc.getText().toString();
            String expiry = mEdtExpiry.getText().toString();
            String expiryMonth = "";
            String expiryYear = "";

            // Focus the field with the first error
            EditText focusField = null;

            // Expiry
            if (TextUtils.isEmpty(expiry)) {
                mEdtExpiry.setError(getString(R.string.error_expiry_date_is_required));
                focusField = mEdtExpiry;
            } else {
                String[] expiryParts = expiry.split("/");
                if (expiryParts.length != 2) {
                    mEdtExpiry.setError(getString(R.string.error_expiry_date_is_not_valid));
                    focusField = mEdtExpiry;
                } else {
                    expiryMonth = expiryParts[0];
                    expiryYear = expiryParts[1];

                    // parse to an int for further validation
                    int month = Integer.parseInt(expiryMonth);
                    int year = Integer.parseInt(expiryYear);

                    // make sure the month is a valid number
                    if (month > 12 || month < 1) {
                        mEdtExpiry.setError(getString(R.string.error_expiry_date_is_not_valid));
                        focusField = mEdtExpiry;
                    } else {
                        if (!DateUtils.isInFuture(1, month, year + 2000)) {
                            mEdtExpiry.setError(getString(R.string.error_expiry_date_is_not_future));
                            focusField = mEdtExpiry;
                        }
                    }
                }
            }

            // CVC
            if (TextUtils.isEmpty(cvc)) {
                mEdtCvc.setError(getString(R.string.error_cvc_is_required));
                focusField = mEdtCvc;
            } else if (!TextUtils.isDigitsOnly(cvc) || (cvc.length() != 3 && cvc.length() != 4)) {
                mEdtCvc.setError(getString(R.string.error_cvc_is_not_valid));
                focusField = mEdtCvc;
            }

            // Card Number
            if (TextUtils.isEmpty(cardNumber)) {
                mEdtCardNumber.setError(getString(R.string.error_card_number_is_required));
                focusField = mEdtCardNumber;
            } else {
                // Check we don't already have this card in the list
                ArrayList<Card> cards = DataManager.INSTANCE.getFreshCards();
                for (Card card : cards) {
                    if (card.getPAN().replace(" ", "").equals(cardNumber.replace(" ", ""))) {
                        mEdtCardNumber.setError(getString(R.string.error_card_number_already_in_use));
                        focusField = mEdtCardNumber;
                        break;
                    }
                }
            }

            // Card holder name
            if (TextUtils.isEmpty(cardholderName)) {
                mEdtCardholderName.setError(getString(R.string.error_cardholder_name_is_required));
                focusField = mEdtCardholderName;
            }

            // apache credit card validator
            CreditCardValidator ccv = new CreditCardValidator();

            if (!ccv.isValid(cardNumber.replace("-", "").replace(" ", ""))) {
                mEdtCardNumber.setError(getString(R.string.error_card_number_not_valid));
                focusField = mEdtCardNumber;
            }

            // If there is no focusField set then the form is valid
            if (focusField != null) {
                focusField.requestFocus();
            } else {
                hideKeyboard();

                if (mIsFirstCard) {
                    // When adding first card we have to set shipping address
                    ShippingAddress shippingAddress = new ShippingAddress();
                    shippingAddress.mName = cardholderName;
                    shippingAddress.mNickname = getString(R.string.verifycard_prefill_nickname);
                    shippingAddress.mLine1 = getString(R.string.verifycard_prefill_billing_address);
                    shippingAddress.mCity = getString(R.string.verifycard_prefill_billing_city);
                    shippingAddress.mZipCode = getString(R.string.verifycard_prefill_billing_zipcode);
                    shippingAddress.mState = getString(R.string.verifycard_prefill_billing_state);
                    // only set as default if it's the first card
                    shippingAddress.bIsDefault = true;
                    mListener.addFirstCard(cardholderName, cardNumber, cvc, expiryMonth, expiryYear,
                            shippingAddress);
                } else {
                    mListener.addCard(cardholderName, cardNumber, cvc, expiryMonth, expiryYear);
                }
            }
        }
    });
}

From source file:org.codehaus.griffon.runtime.validation.constraints.CreditCardConstraint.java

@Override
protected void processValidate(@Nonnull Object target, Object propertyValue, @Nonnull Errors errors) {
    if (!creditCard) {
        return;//from   w  ww . ja  va  2s  . com
    }

    CreditCardValidator validator = new CreditCardValidator();

    if (!validator.isValid(String.valueOf(propertyValue))) {
        Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };
        rejectValue(target, errors, DEFAULT_INVALID_CREDIT_CARD_MESSAGE_CODE,
                VALIDATION_DSL_NAME + INVALID_SUFFIX, args);
    }
}

From source file:org.grails.validation.CreditCardConstraint.java

@Override
protected void processValidate(Object target, Object propertyValue, Errors errors) {
    if (!creditCard) {
        return;//from  w  w  w .j  av  a  2 s.c o m
    }

    CreditCardValidator validator = new CreditCardValidator();

    if (!validator.isValid(propertyValue.toString())) {
        Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue };
        rejectValue(target, errors, ConstrainedProperty.DEFAULT_INVALID_CREDIT_CARD_MESSAGE_CODE,
                ConstrainedProperty.CREDIT_CARD_CONSTRAINT + ConstrainedProperty.INVALID_SUFFIX, args);
    }
}

From source file:org.moqui.impl.service.ServiceDefinition.java

private boolean validateParameterSingle(MNode valNode, String parameterName, Object pv,
        ExecutionContextImpl eci) {/*from  w ww  . j  ava 2s.  c o m*/
    // should never be null (caller checks) but check just in case
    if (pv == null)
        return true;

    String validateName = valNode.getName();
    if ("val-or".equals(validateName)) {
        boolean anyPass = false;
        for (MNode child : valNode.getChildren())
            if (validateParameterSingle(child, parameterName, pv, eci))
                anyPass = true;
        return anyPass;
    } else if ("val-and".equals(validateName)) {
        boolean allPass = true;
        for (MNode child : valNode.getChildren())
            if (!validateParameterSingle(child, parameterName, pv, eci))
                allPass = false;
        return allPass;
    } else if ("val-not".equals(validateName)) {
        boolean allPass = true;
        for (MNode child : valNode.getChildren())
            if (!validateParameterSingle(child, parameterName, pv, eci))
                allPass = false;
        return !allPass;
    } else if ("matches".equals(validateName)) {
        if (!(pv instanceof CharSequence)) {
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand(
                            "Value entered (${pv}) is not a string, cannot do matches validation.", "", map),
                    null);
            return false;
        }

        String pvString = pv.toString();
        String regexp = valNode.attribute("regexp");
        if (regexp != null && !regexp.isEmpty() && !pvString.matches(regexp)) {
            // a message attribute should always be there, but just in case we'll have a default
            final String message = valNode.attribute("message");
            Map<String, Object> map = new HashMap<>(2);
            map.put("pv", pv);
            map.put("regexp", regexp);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource()
                            .expand(message != null && !message.isEmpty() ? message
                                    : "Value entered (${pv}) did not match expression: ${regexp}", "", map),
                    null);
            return false;
        }

        return true;
    } else if ("number-range".equals(validateName)) {
        BigDecimal bdVal = new BigDecimal(pv.toString());
        String minStr = valNode.attribute("min");
        if (minStr != null && !minStr.isEmpty()) {
            BigDecimal min = new BigDecimal(minStr);
            if ("false".equals(valNode.attribute("min-include-equals"))) {
                if (bdVal.compareTo(min) <= 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("min", min);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is less than or equal to ${min} must be greater than.",
                                    "", map),
                            null);
                    return false;
                }
            } else {
                if (bdVal.compareTo(min) < 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("min", min);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is less than ${min} and must be greater than or equal to.",
                                    "", map),
                            null);
                    return false;
                }
            }
        }

        String maxStr = valNode.attribute("max");
        if (maxStr != null && !maxStr.isEmpty()) {
            BigDecimal max = new BigDecimal(maxStr);
            if ("true".equals(valNode.attribute("max-include-equals"))) {
                if (bdVal.compareTo(max) > 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("max", max);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is greater than ${max} and must be less than or equal to.",
                                    "", map),
                            null);
                    return false;
                }

            } else {
                if (bdVal.compareTo(max) >= 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("max", max);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is greater than or equal to ${max} and must be less than.",
                                    "", map),
                            null);
                    return false;
                }
            }
        }

        return true;
    } else if ("number-integer".equals(validateName)) {
        try {
            new BigInteger(pv.toString());
        } catch (NumberFormatException e) {
            if (logger.isTraceEnabled())
                logger.trace(
                        "Adding error message for NumberFormatException for BigInteger parse: " + e.toString());
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value [${pv}] is not a whole (integer) number.", "", map), null);
            return false;
        }

        return true;
    } else if ("number-decimal".equals(validateName)) {
        try {
            new BigDecimal(pv.toString());
        } catch (NumberFormatException e) {
            if (logger.isTraceEnabled())
                logger.trace(
                        "Adding error message for NumberFormatException for BigDecimal parse: " + e.toString());
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value [${pv}] is not a decimal number.", "", map), null);
            return false;
        }

        return true;
    } else if ("text-length".equals(validateName)) {
        String str = pv.toString();
        String minStr = valNode.attribute("min");
        if (minStr != null && !minStr.isEmpty()) {
            int min = Integer.parseInt(minStr);
            if (str.length() < min) {
                Map<String, Object> map = new HashMap<>(3);
                map.put("pv", pv);
                map.put("str", str);
                map.put("minStr", minStr);
                eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand(
                        "Value entered (${pv}), length ${str.length()}, is shorter than ${minStr} characters.",
                        "", map), null);
                return false;
            }

        }

        String maxStr = valNode.attribute("max");
        if (maxStr != null && !maxStr.isEmpty()) {
            int max = Integer.parseInt(maxStr);
            if (str.length() > max) {
                Map<String, Object> map = new HashMap<>(3);
                map.put("pv", pv);
                map.put("str", str);
                map.put("maxStr", maxStr);
                eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand(
                        "Value entered (${pv}), length ${str.length()}, is longer than ${maxStr} characters.",
                        "", map), null);
                return false;
            }
        }

        return true;
    } else if ("text-email".equals(validateName)) {
        String str = pv.toString();
        if (!emailValidator.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value entered (${str}) is not a valid email address.", "", map),
                    null);
            return false;
        }

        return true;
    } else if ("text-url".equals(validateName)) {
        String str = pv.toString();
        if (!urlValidator.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value entered (${str}) is not a valid URL.", "", map), null);
            return false;
        }

        return true;
    } else if ("text-letters".equals(validateName)) {
        String str = pv.toString();
        for (char c : str.toCharArray()) {
            if (!Character.isLetter(c)) {
                Map<String, String> map = new HashMap<>(1);
                map.put("str", str);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${str}) must have only letters.", "", map),
                        null);
                return false;
            }
        }

        return true;
    } else if ("text-digits".equals(validateName)) {
        String str = pv.toString();
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                Map<String, String> map = new HashMap<>(1);
                map.put("str", str);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value [${str}] must have only digits.", "", map), null);
                return false;
            }
        }

        return true;
    } else if ("time-range".equals(validateName)) {
        Calendar cal;
        String format = valNode.attribute("format");
        if (pv instanceof CharSequence) {
            cal = eci.getL10n().parseDateTime(pv.toString(), format);
        } else {
            // try letting groovy convert it
            cal = Calendar.getInstance();
            // TODO: not sure if this will work: ((pv as java.util.Date).getTime())
            cal.setTimeInMillis((DefaultGroovyMethods.asType(pv, Date.class)).getTime());
        }

        String after = valNode.attribute("after");
        if (after != null && !after.isEmpty()) {
            // handle after date/time/date-time depending on type of parameter, support "now" too
            Calendar compareCal;
            if ("now".equals(after)) {
                compareCal = Calendar.getInstance();
                compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime());
            } else {
                compareCal = eci.getL10n().parseDateTime(after, format);
            }
            if (cal != null && !cal.after(compareCal)) {
                Map<String, Object> map = new HashMap<>(2);
                map.put("pv", pv);
                map.put("after", after);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${pv}) is before ${after}.", "", map), null);
                return false;
            }
        }

        String before = valNode.attribute("before");
        if (before != null && !before.isEmpty()) {
            // handle after date/time/date-time depending on type of parameter, support "now" too
            Calendar compareCal;
            if ("now".equals(before)) {
                compareCal = Calendar.getInstance();
                compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime());
            } else {
                compareCal = eci.getL10n().parseDateTime(before, format);
            }
            if (cal != null && !cal.before(compareCal)) {
                Map<String, Object> map = new HashMap<>(1);
                map.put("pv", pv);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${pv}) is after ${before}.", "", map), null);
                return false;
            }
        }

        return true;
    } else if ("credit-card".equals(validateName)) {
        long creditCardTypes = 0;
        String types = valNode.attribute("types");
        if (types != null && !types.isEmpty()) {
            for (String cts : types.split(","))
                creditCardTypes += creditCardTypeMap.get(cts.trim());
        } else {
            creditCardTypes = allCreditCards;
        }

        CreditCardValidator ccv = new CreditCardValidator(creditCardTypes);
        String str = pv.toString();
        if (!ccv.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource()
                    .expand("Value entered (${str}) is not a valid credit card number.", "", map), null);
            return false;
        }

        return true;
    }
    // shouldn't get here, but just in case
    return true;
}

From source file:paquete.Ventana.java

private void jButtonComprobarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonComprobarActionPerformed

    // Validamos la Tarjeta de Credito
    if (!jTextTarjeta.getText().equals("")) {

        CreditCardValidator validaTarjeta = new CreditCardValidator();

        if (validaTarjeta.isValid(jTextTarjeta.getText()))
            JOptionPane.showMessageDialog(this, "Tarjeta Vlida", "Correcto", JOptionPane.INFORMATION_MESSAGE);
        else//from   www . j  a va  2s .  c o m
            JOptionPane.showMessageDialog(this, "Tarjeta Invlida", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:proyectoprestamos.DatosUsuario.java

private void jButtonValidarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonValidarActionPerformed
    CreditCardValidator ccValidator = new CreditCardValidator();
    boolean numeroTarjeta = ccValidator.isValid(tarjetaCredito.getText());
    String mensaje = numeroTarjeta ? "Tarjeta validada" : "Tarjeta Incorrecta";
    JOptionPane.showMessageDialog(this, mensaje);
}