Reputation: 940
I'm trying to validate the text of a JTextField
. The content of this textfield should be something like this 66.160507, -153.369141
or 66.160507,-153.369141
(without whitespace after the comma).
So far I validate only the range for both latitude and longitude.
Here:
String [] splitted = jtextField.getText().split(",");
double latitude = Double.parseDouble(splitted[0]);
double longitude = Double.parseDouble(splitted[1])
if(latitude < -90 || latitude > 90)
return false;
else
continue;
if(longitude < -180 || longitude > 180)
return false;
else
continue;
but now how can I check whether the text in the JTextField
is in the right format and order? I need to validate these two cases:
must be a double -> must be a comma -> must be a whitespace -> must be a double
must be a double -> must be a comma -> must be a double
Upvotes: 3
Views: 5165
Reputation: 1116
^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$
^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$
public boolean validateLong(String longitude) {
booelan isValid = false;
if (longitude != null) {
String regexValidateLongitude = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$";
isValid = longitude.trim().matches(regexValidateLongitude);
}
return isValid;
}
public boolean validateLat(String latitude) {
booelan isValid = false;
if (latitude != null) {
String regexValidateLatitude = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$";
isValid = latitude.matches(regexValidateLatitude);
}
return isValid;
}
Upvotes: 1
Reputation: 79808
One option would be to use a regular expression to validate the form of what's in your text field. You can read up on the different symbols you can use in a regular expression at the Javadoc for the Pattern class, but some of the ones you might use would be
*
any number of matches of what goes before (including none);+
one or more matches of what goes before;?
zero or one matches of what goes before;[ ]
a range of characters. \.
a dot (the backslash will need escaping if it's in a Java String
literal),\s
any whitespace (and this backslash will also need escaping in a String
literal).Putting this all together you might come up with a regular expression like this.
-?[1-9][0-9]*(\.[0-9]+)?,\s*-?[1-9][0-9]*(\.[0-9]+)?
to match a pair of latitude and longitude.
This matches
You could then write code like this.
String textValue = jtextField.getText();
String twoDoublesRegularExpression = "-?[1-9][0-9]*(\\.[0-9]+)?,\\s*-?[1-9][0-9]*(\\.[0-9]+)?";
if (textValue.matches(twoDoublesRegularExpression)) {
// this value is OK
}
Upvotes: 4