Codename One - RegexConstraint to check a valid phone number

六月ゝ 毕业季﹏ 提交于 2020-01-03 02:22:16

问题


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.

(Note: this question is not for generic Java, but only for Codename One. The class "CountryCodePicker" extends the class "Button": I reported it to make it clear that the phone number and the country code are separated)

    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);

回答1:


[rant] Personally I really hate regex as I find it damn unreadable for anything other than trivial validation. [/rant]

So I would prefer this:

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})";


来源:https://stackoverflow.com/questions/48481888/codename-one-regexconstraint-to-check-a-valid-phone-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!