Validation of mobile number field

2.2k views Asked by At

I want to know what's wrong with this code? I am taking my input in the textbox(A 10-digit mobile number). My problem is that, this code all the time prints else statement even if my input is correct.

mobNo=textMobNo.getText();

textMobNo.addFocusListener(new FocusListener() {

    @Override
    public void focusLost(FocusEvent arg0) {
        // TODO Auto-generated method stub

        Pattern pattern = Pattern.compile("^[789]\\d{9}$");
        Matcher matcher = pattern.matcher(mobNo);

        if (matcher.matches()){
            System.out.println("valid");
        }
        else{
            System.out.println("invalid");
        }       
    }

    @Override
    public void focusGained(FocusEvent arg0) {
        // TODO Auto-generated method stub

    };
});
1

There are 1 answers

0
arcy On BEST ANSWER

You are obtaining text from your text field, THEN adding a focusListener. At some later time, the focus listener is fired, which then uses the text you got from your field before the focus listener was active. Yeah, that text is probably from before anything was typed in the field; that would explain it being an empty string. Try getting the text IN the focus listener... (hint - the string you get from the text field is not continually updated as text is typed in the field...)