public class RowFunctionValidator extends Object implements RowValidator
An empty or null first row is considered invalid.
As with all row validators the assumption is you have control of the data and have skipped any initial empty lines AND that your validator checks the size or handles the IndexOutOfBoundsException.
There are several examples coded in the RowFunctionValidatorTest but here are a couple to give you the idea of the flexibility this validator offers.
private static final String[] GOOD_ROW = {"8675309", "Firstname", "M", "Lastname", "Dec 06, 1951"}; private static final String[] BAD_ROW = {"not a number", "not capitialized", "not an initial", "Not Single word", "12/06/51"}; private static final String[] LONG_ROW = {"8675309", "Firstname", "M", "Lastname", "Dec 06, 1951", "More data"}; private static final String[] SHORT_ROW = {"8675309", "Firstname", "Lastname", "Dec 06, 1951"}; private static final Function<String[], Boolean> THIRD_ELEMENT_IS_MIDDLE_INITIAL = (x) -> { return x.length > 2 && x[2].matches("^[A-Z]$"); }; private static final Function<String[], Boolean> ROW_MUST_HAVE_FIVE_ELEMENTS = (x) -> { return (x.length == 5); };
@Test
@DisplayName("Simple test to show checking an middle initial")
public void thirdElementIsMiddleInitial() { validator = new RowFunctionValidator(THIRD_ELEMENT_IS_MIDDLE_INITIAL, "The third element must be the middle initial."); assertTrue(validator.isValid(GOOD_ROW)); assertFalse(validator.isValid(BAD_ROW)); }
@Test
@DisplayName("The row must have a specific number of elements in order to be valid.")
public void numberOfElementsInARow() { validator = new RowFunctionValidator(ROW_MUST_HAVE_FIVE_ELEMENTS, "A Row can have only five elements."); assertTrue(validator.isValid(GOOD_ROW)); assertFalse(validator.isValid(LONG_ROW)); assertFalse(validator.isValid(SHORT_ROW)); }
Constructor and Description |
---|
RowFunctionValidator(Function<String[],Boolean> testFunction,
String failureMessage)
Default Constructor.
|
Modifier and Type | Method and Description |
---|---|
boolean |
isValid(String[] row)
Performs the validation check on the string and returns the result.
|
void |
validate(String[] row)
Performs the validation check on the row (an array of
String s)
and throws an exception if invalid. |
public boolean isValid(String[] row)
RowValidator
isValid
in interface RowValidator
row
- Array of strings to be validatedtrue
if the row is valid, false
otherwisepublic void validate(String[] row) throws CsvValidationException
RowValidator
String
s)
and throws an exception if invalid.validate
in interface RowValidator
row
- Array of String
s to be validated.CsvValidationException
- Thrown if invalid. Should contain a
message describing the error.Copyright © 2005–2023. All rights reserved.