代号One-RegexConstraint检查有效的电话号码 [英] Codename One - RegexConstraint to check a valid phone number
问题描述
在以下代码中,RegexConstraint不起作用,因为电话号码结果始终不正确。怎么了?我需要检查手机号码(无国家代码)。例如,输入3652312453应该是正确的,但是在以下代码中它被评估为不正确。
我从评论中链接的讨论中复制了正则表达式:我唯一的要求是有效的电话号码。
In the following code, the RegexConstraint doesn't work, because the phone number results always incorrect. What's wrong? I need to check a mobile phone number (without the country code). For example, the input 3652312453 should be correct, but in the following code it's evaluated as incorrect. I copied the regex from the discussion linked in the comment: my only requirement is a valid phone number.
(注意:此问题不是适用于通用Java,但仅适用于代号One。类 CountryCodePicker扩展了类 Button:我报告说是为了清楚地表明电话号码和国家/地区代码是分开的)
TextModeLayout tl = new TextModeLayout(1, 1);
Container loginContainer = new Container(tl);
TextComponent phone = new TextComponent().label("PHONE").errorMessage("INVALID-PHONE");
CountryCodePicker countryCode = new CountryCodePicker();
phone.getField().setConstraint(TextArea.PHONENUMBER);
loginContainer.add(phone);
Container loginContainerWithCodePicker = new Container(new BoxLayout(BoxLayout.X_AXIS_NO_GROW));
loginContainerWithCodePicker.add(countryCode).add(loginContainer);
// https://stackoverflow.com/questions/8634139/phone-validation-regex
String phoneRegEx = "/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/";
val.addConstraint(phone, new RegexConstraint(phoneRegEx, "NOT-VALID-NUMBER"));
Button loginButton = new Button("LOG-IN");
val.addSubmitButtons(loginButton);
推荐答案
[rant]
我个人真的很讨厌正则表达式,除了琐碎的验证之外,我发现它根本无法读取。
[/ rant]
[rant] Personally I really hate regex as I find it damn unreadable for anything other than trivial validation. [/rant]
所以我更愿意这样做:
val.addConstraint(phone, new Constraint() {
public boolean isValid(Object value) {
String v = (String)value;
for(int i = 0 ; i < v.length() ; i++) {
char c = v.charAt(i);
if(c >= '0' && c <= '9' || c == '+' || c == '-') {
continue;
}
return false;
}
return true;
}
public String getDefaultFailMessage() {
return "Must be valid phone number";
}
});
但是,我猜测正则表达式对您失败的原因与斜杠的语法有关:
However, I'm guessing the reason the regex failed for you is related to the syntax with the slashes:
String phoneRegEx = "^\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})";
这篇关于代号One-RegexConstraint检查有效的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!