Search code examples
javaintellij-ideamaskformatter

Format string with MaskFormatter throws "Invalid character" exception


I have a function in which I need to set a string to the following format : #####-####-## and padded with leading zeroes.

eg:

1234567 will become 00001-2345-67

98765432109 will become 98765-4321-09

I'm using MaskFormatter and my impression from the documentation was that A represented any letter or digit, and that setPlaceHolderCharacter would pad the string.

I know technically it's for use with text fields but had hoped I could use it in a back-end function, if not is there a different component i should be using?

I have this code below but it throws an exception java.text.ParseException: Invalid character: 1 when it hits mask.valueToString(ndc)

public class NdcFormatter implements MapFunction<Purchase, Purchase> {

    private final String maskFormat = "AAAAA-AAAA-AA";
    private final Character placeholder = '0';


    @Override
    public Purchase map(Purchase purchase) throws ParseException {
        if(purchase != null){

            String ndc = purchase.getNdc();
            MaskFormatter mask = new MaskFormatter(maskFormat);
            mask.setPlaceholderCharacter(placeholder);
            String result = mask.valueToString(ndc);

            purchase.setNdc(result);

        }

        return purchase;
    }
}

Solution

  • Here is how to fix ERROR java.text.ParseException: Invalid character: ... in MaskFormatter

    Solution the error is in valueToString method, you have to add this line of code :

    mask.setValueContainsLiteralCharacters(false);
    

    but you will get a problem like that :

    • when you set 1234567 it will return you 12345-6700-00
    • to get 00001-2345-67 you have to pass 00001234567

    so you have to fix your input value before formatting .

    here is the complete code :

    public class NdcFormatter implements MapFunction<Purchase, Purchase> {
    
        private final String maskFormat = "AAAAA-AAAA-AA";
        private final Character placeholder = '0';
    
    
        @Override
        public Purchase map(Purchase purchase) throws ParseException {
            if(purchase != null){
    
                String ndc = purchase.getNdc();
                MaskFormatter mask = new MaskFormatter(maskFormat);
                mask.setPlaceholderCharacter(placeholder);
                mask.setValueContainsLiteralCharacters(false);
                String result = mask.valueToString(ndc);
    
                purchase.setNdc(result);
    
            }
    
            return purchase;
        }
    }
    

    to pad the leading zeroes by yourself here is a simple code example.

        if(ndc.length() < maskFormat.length()) {
            String pad = "0";
            for(int i = 0; i < maskFormat.length() -ndc.length() - 3; i++ ) {
                pad = pad + "0" ;
            }
            ndc = pad + ndc;
        }