Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WW-3952: Credit card validator #130

Merged
merged 7 commits into from
Apr 24, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ else if (a instanceof EmailValidator) {
result.add(temp);
}
}
// Process CrediCardValidator
else if (a instanceof CreditCardValidator) {
CreditCardValidator v = (CreditCardValidator) a;
ValidatorConfig temp = processCreditCardValidatorAnnotation(v, fieldName, methodName);
if (temp != null) {
result.add(temp);
}
}
// Process FieldExpressionValidator
else if (a instanceof FieldExpressionValidator) {
FieldExpressionValidator v = (FieldExpressionValidator) a;
Expand Down Expand Up @@ -263,6 +271,15 @@ private void processValidationAnnotation(Annotation a, String fieldName, String
}
}
}
CreditCardValidator[] ccv = validations.creditCards();
if (ccv != null) {
for (CreditCardValidator v : ccv) {
ValidatorConfig temp = processCreditCardValidatorAnnotation(v, fieldName, methodName);
if (temp != null) {
result.add(temp);
}
}
}
FieldExpressionValidator[] fev = validations.fieldExpressions();
if (fev != null) {
for (FieldExpressionValidator v : fev) {
Expand Down Expand Up @@ -786,6 +803,28 @@ private ValidatorConfig processEmailValidatorAnnotation(EmailValidator v, String
.build();
}

private ValidatorConfig processCreditCardValidatorAnnotation(CreditCardValidator v, String fieldName, String methodName) {
String validatorType = "creditcard";

Map<String, Object> params = new HashMap<>();

if (fieldName != null) {
params.put("fieldName", fieldName);
} else if (StringUtils.isNotEmpty(v.fieldName())) {
params.put("fieldName", v.fieldName());
}

validatorFactory.lookupRegisteredValidatorType(validatorType);
return new ValidatorConfig.Builder(validatorType)
.addParams(params)
.addParam("methodName", methodName)
.shortCircuit(v.shortCircuit())
.defaultMessage(v.message())
.messageKey(v.key())
.messageParams(v.messageParams())
.build();
}

private ValidatorConfig processDateRangeFieldValidatorAnnotation(DateRangeFieldValidator v, String fieldName, String methodName) {
String validatorType = "date";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2002-2006,2009 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.opensymphony.xwork2.validator.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* This validator checks that a field is a valid credit card.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CreditCardValidator {

/**
* @return The default error message for this validator.
* NOTE: It is required to set a message, if you are not using the message key for 18n lookup!
*/
String message() default "";

/**
* @return The message key to lookup for i18n.
*/
String key() default "";

/**
* @return Additional params to be used to customize message - will be evaluated against the Value Stack
*/
String[] messageParams() default {};

/**
* @return The optional fieldName for SIMPLE validator types.
*/
String fieldName() default "";

/**
* If this is activated, the validator will be used as short-circuit.
*
* Adds the short-circuit='true' attribute value if <tt>true</tt>.
*
* @return true if validator will be used as short-circuit. Default is false.
*/
boolean shortCircuit() default false;

/**
* @return The validation type for this field/method.
*/
ValidatorType type() default ValidatorType.FIELD;

}
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@

EmailValidator[] emails() default {};

CreditCardValidator[] creditCards() default {};

FieldExpressionValidator[] fieldExpressions() default {};

IntRangeFieldValidator[] intRangeFields() default {};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright 2002-2006,2009 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.opensymphony.xwork2.validator.validators;


import org.apache.commons.lang3.StringUtils;

/**
* CreditCardFieldValidator checks that a given String/Array/Collection field,
* if not empty, is a valid credit card number.
*/
public class CreditCardValidator extends RegexFieldValidator {

public static final String CREDIT_CARD_PATTERN =
"^(?:4[0-9]{12}(?:[0-9]{3})?" + // Visa
"|(?:5[1-5][0-9]{2}" + // MasterCard
"|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}" +
"|3[47][0-9]{13}" + // American Express
"|3(?:0[0-5]|[68][0-9])[0-9]{11}" + // Diners Club
"|6(?:011|5[0-9]{2})[0-9]{12}" + // Discover
"|(?:2131|1800|35\\d{3})\\d{11}" + // JCB
")$";

public CreditCardValidator() {
setRegex(CREDIT_CARD_PATTERN);
setCaseSensitive(false);
}

protected void validateFieldValue(Object object, String value, String regexToUse) {
super.validateFieldValue(object, StringUtils.deleteWhitespace(value), regexToUse);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,14 @@ protected void validateFieldValue(Object object, String value, String regexToUse
compare = compare.trim();
}

Matcher matcher = pattern.matcher(compare);
if (!matcher.matches()) {
addFieldError(fieldName, object);
try {
setCurrentValue(compare);
Matcher matcher = pattern.matcher(compare);
if (!matcher.matches()) {
addFieldError(fieldName, object);
}
} finally {
setCurrentValue(null);
}
}

Expand Down
28 changes: 14 additions & 14 deletions core/src/main/resources/template/xhtml/form-close-validate.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ END SNIPPET: supported-validators
-->
var getFieldValue = function(field) {
var type = field.type ? field.type : field[0].type;
if (type == 'select-one' || type == 'select-multiple') {
return (field.selectedIndex == -1 ? "" : field.options[field.selectedIndex].value);
} else if (type == 'checkbox' || type == 'radio') {
if (type === 'select-one' || type === 'select-multiple') {
return (field.selectedIndex === -1 ? "" : field.options[field.selectedIndex].value);
} else if (type === 'checkbox' || type === 'radio') {
if (!field.length) {
field = [field];
}
Expand Down Expand Up @@ -79,25 +79,25 @@ END SNIPPET: supported-validators
var fieldValue = getFieldValue(field);

<#if validator.validatorType = "required">
if (fieldValue == "") {
if (fieldValue === "") {
addError(field, error);
errors = true;
<#if validator.shortCircuit>continueValidation = false;</#if>
}
<#elseif validator.validatorType = "requiredstring">
if (continueValidation && fieldValue != null && (fieldValue == "" || fieldValue.replace(/^\s+|\s+$/g,"").length == 0)) {
if (continueValidation && fieldValue !== null && (fieldValue === "" || fieldValue.replace(/^\s+|\s+$/g,"").length === 0)) {
addError(field, error);
errors = true;
<#if validator.shortCircuit>continueValidation = false;</#if>
}
<#elseif validator.validatorType = "stringlength">
if (continueValidation && fieldValue != null) {
if (continueValidation && fieldValue !== null) {
var value = fieldValue;
<#if validator.trim>
//trim field value
while (value.substring(0,1) == ' ')
while (value.substring(0,1) === ' ')
value = value.substring(1, value.length);
while (value.substring(value.length-1, value.length) == ' ')
while (value.substring(value.length-1, value.length) === ' ')
value = value.substring(0, value.length-1);
</#if>
if ((${validator.minLength?c} > -1 && value.length < ${validator.minLength?c}) ||
Expand All @@ -108,25 +108,25 @@ END SNIPPET: supported-validators
}
}
<#elseif validator.validatorType = "regex">
if (continueValidation && fieldValue != null && !fieldValue.match("${validator.regex?js_string}")) {
if (continueValidation && fieldValue !== null && !fieldValue.match("${validator.regex?js_string}")) {
addError(field, error);
errors = true;
<#if validator.shortCircuit>continueValidation = false;</#if>
}
<#elseif validator.validatorType = "email">
if (continueValidation && fieldValue != null && fieldValue.length > 0 && fieldValue.match(/${validator.regex}/i)==null) {
<#elseif validator.validatorType = "email" || validator.validatorType = "creditcard">
if (continueValidation && fieldValue !== null && fieldValue.length > 0 && fieldValue.match(/${validator.regex}/i) === null) {
addError(field, error);
errors = true;
<#if validator.shortCircuit>continueValidation = false;</#if>
}
<#elseif validator.validatorType = "url">
if (continueValidation && fieldValue != null && fieldValue.length > 0 && fieldValue.match(/${validator.urlRegex}/i)==null) {
if (continueValidation && fieldValue !== null && fieldValue.length > 0 && fieldValue.match(/${validator.urlRegex}/i) === null) {
addError(field, error);
errors = true;
<#if validator.shortCircuit>continueValidation = false;</#if>
}
<#elseif validator.validatorType = "int" || validator.validatorType = "short">
if (continueValidation && fieldValue != null) {
if (continueValidation && fieldValue !== null) {
if (<#if validator.min??>parseInt(fieldValue) <
${validator.min?c}<#else>false</#if> ||
<#if validator.max??>parseInt(fieldValue) >
Expand All @@ -137,7 +137,7 @@ END SNIPPET: supported-validators
}
}
<#elseif validator.validatorType = "double">
if (continueValidation && fieldValue != null) {
if (continueValidation && fieldValue !== null) {
var value = parseFloat(fieldValue);
if (<#if validator.minInclusive??>value < ${validator.minInclusive?c}<#else>false</#if> ||
<#if validator.maxInclusive??>value > ${validator.maxInclusive?c}<#else>false</#if> ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.ConditionalVisitorFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ConversionErrorFieldValidator;
import com.opensymphony.xwork2.validator.annotations.CreditCardValidator;
import com.opensymphony.xwork2.validator.annotations.CustomValidator;
import com.opensymphony.xwork2.validator.annotations.DateRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.DoubleRangeFieldValidator;
Expand Down Expand Up @@ -45,6 +46,8 @@ public class AnnotationValidationAction extends ActionSupport {
messageParams = {"one", "two", "three"})
@EmailValidator(message = "Foo isn't a valid e-mail!", fieldName = "foo", key = "email.key",
messageParams = {"one", "two", "three"}, shortCircuit = true)
@CreditCardValidator(message = "Foo isn't a valid credit card!", fieldName = "foo", key = "creditCard.key",
messageParams = {"one", "two", "three"}, shortCircuit = true)
@ExpressionValidator(expression = "true", message = "Is not true!", key = "expression.key",
messageParams = {"one", "two", "three"}, shortCircuit = true)
@FieldExpressionValidator(expression = "true", fieldName = "foo", key = "fieldexpression.key", message = "It is not true!",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.opensymphony.xwork2.util.location.LocatableProperties;
import com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator;
import com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator;
import com.opensymphony.xwork2.validator.validators.CreditCardValidator;
import com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator;
import com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator;
import com.opensymphony.xwork2.validator.validators.EmailValidator;
Expand Down Expand Up @@ -50,7 +51,7 @@ public void testValidationAnnotation() throws Exception {
List<Validator> validators = manager.getValidators(AnnotationValidationAction.class, null);

// then
assertEquals(validators.size(), 16);
assertEquals(validators.size(), 17);
for (Validator validator : validators) {
validate(validator);
}
Expand Down Expand Up @@ -89,6 +90,8 @@ private void validate(Validator validator) throws Exception {
validateDoubleRangeFieldValidator((DoubleRangeFieldValidator) validator);
} else if (validator.getValidatorType().equals("email")) {
validateEmailValidator((EmailValidator) validator);
} else if (validator.getValidatorType().equals("creditcard")) {
validateCreditCardValidator((CreditCardValidator) validator);
} else if (validator.getValidatorType().equals("expression")) {
validateExpressionValidator((ExpressionValidator) validator);
} else if (validator.getValidatorType().equals("fieldexpression")) {
Expand Down Expand Up @@ -203,6 +206,17 @@ private void validateEmailValidator(EmailValidator validator) {
assertEquals(true, validator.isTrimed());
}

private void validateCreditCardValidator(CreditCardValidator validator) {
assertEquals("foo", validator.getFieldName());
assertEquals(CreditCardValidator.CREDIT_CARD_PATTERN, validator.getRegex());
assertEquals("Foo isn't a valid credit card!", validator.getDefaultMessage());
assertEquals("creditCard.key", validator.getMessageKey());
assertTrue(Arrays.equals(new String[]{"one", "two", "three"}, validator.getMessageParameters()));
assertEquals(true, validator.isShortCircuit());
assertEquals(false, validator.isCaseSensitive());
assertEquals(true, validator.isTrimed());
}

private void validateDoubleRangeFieldValidator(DoubleRangeFieldValidator validator) {
assertEquals("foo", validator.getFieldName());
assertEquals("double.key", validator.getMessageKey());
Expand Down
Loading