Question

I have 2 QueryParam's

Date = "YYYY-MM-DD" Country = "3 letters"

I need to return 400 error if the inputs are invalid, I don't have to check if a date is maybe in future or that the country doesn't exist, I have to check that the format is valid. That country is always 3 letters and not some weird symbols and date is (number-number-number-number --- number-number --- number-number).

Was it helpful?

Solution

A very naive solution I can think of right now is as follows. If you are not comfortable using regex, for date you can simply try string.split() or any equivalent java method which splits based on a certain character. After that just try to check if all three splits are valid numbers using Integer.parseInt(). For letters you can check if each character is in the range that you are requiring by using a simple ascii value comparison. However, regex will always be better.

OTHER TIPS

You can use the String.split() function which give you an array of string (3 strings in your case) and then compare the value in this array as you desired by using Integer.parseInt()
For example :

String date = "2010-02-12";
String arr[] = date.split("-");
int day = Integer.parseInt(arr[2]);
if(day < 1 || day > 31)
 System.out.println("Not a good day !");

This code is not tested but it show you how it works.
Be aware that Integer.parseInt() can throws NumberFormatException, so catch it and then you can raise your error 400.
It is not as nice as regex, but it will work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top