Java Textfield电子邮件必须包含某些字符

时间:2015-11-08 01:52:30

标签: java validation email textbox textfield

我想为电子邮件地址创建一个Java textfield,当我点击提交时,它必须在文本中包含@.以供验证。

我该怎么做?

http://imgur.com/nYNBy1K

我的代码:

private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
    if(txtName.getText().trim().equals(""))
    {
        JOptionPane.showMessageDialog(null, "Must have name");
        jlblNameVer.setVisible(true);
    }

    //Phone Number Validation
     if(txtPhoneNum.getText().length() < 10)
    {
        JOptionPane.showMessageDialog(null, "Must atleast 10 characters");
    }

}  

1 个答案:

答案 0 :(得分:0)

你没有检查null,你可能会遇到空指针异常..请看一下代码。

if(txtName==null || txtName.getText()== null ||txtName.getText().trim().length()==0)
        {
            //must have name message
        }

        //Phone Number Validation
         if(txtPhoneNum==null || txtPhoneNum.getText()==null || txtPhoneNum.getText().length() < 10)
        {
            //Must atleast 10 characters
        }

         if(txtEmailAddr==null || txtEmailAddr.getText()== null ||
                 !(txtEmailAddr.getText().trim().contains("@") && txtEmailAddr.getText().trim().contains(".")))
        {
             //must have valid email address
         }