なんだよーこいつもすげーらくじゃーん
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>3.6</version>
</dependency>
String tel = "0451234567";
Phonenumber.PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(tel, "JP");
tel = PHONE_NUMBER_UTIL.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
System.out.println(tel);
045-123-4567
になるぜ。
SpringのCustomEditor使ってこんな風にもねぇ。
public class PhoneNumberEditor extends PropertyEditorSupport {
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
@Override
public void setAsText(String text) {
if (!StringUtils.hasText(text)) {
setValue(null);
}
else {
try {
Phonenumber.PhoneNumber phoneNumber = PHONE_NUMBER_UTIL.parse(text, "JP");
text = PHONE_NUMBER_UTIL.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
}
catch (NumberParseException e) {
// Do Nothing
}
setValue(text);
}
}
}
@Controller
@RequestMapping(value="/hoge")
public class HogeController {
@InitBinder(FORM_MODEL_KEY)
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
binder.registerCustomEditor(String.class, "tel", new PostalCodeEditor());
}
...
}