I want to make a Java textfield for an email address, when I click submit it must contain an # and . in text for validation.
How do I do that?
My code:
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");
}
}
you are not checking null's, You might run into null pointer exception.. please take a look at code.
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
}
Related
I am trying to print any email addresses that are invalid. To be invalid, the email addresses need to not contain an # sign, a period, or a space. The code I have is returning email addresses that do not have an # sign or a period, but they are not returning email addresses that have a space in them.
public static void print_emails(){
for (int i = 0; i < student.size(); i++) {
if (student.get(i).getEmail().contains("#") && student.get(i).getEmail().contains(".") && student.get(i).getEmail().contains("")){
System.out.println("Scanning Roster");
}
else if (student.get(i).getEmail().contains("\\s")){
System.out.println("Invalid email address, " + student.get(i).getEmail());
}
else {
System.out.println("Invalid email address, " + student.get(i).getEmail());
}
}
}
A better way of doing it would be to match the email string against a regular expression. The following should work:
^[A-Za-z0-9+_.-]+#(.+)$
This is a very simple one, which you could make increasingly complex to suit your needs. Currently, this one ensures:
1) A-Z and a-z characters are allowed
2) 0-9 numbers are allowed
3) The email may contain only dot(.), dash(-) and underscore(_)
As well as allowing the # symbol in the correct place.
contains() is expecting a CharSequence. Use regex instead:
else if (studentList.get(i).getEmail().matches(".*\\s.*"))
You can modify your code to include this:
public static void print_invalid_emails()
{
for (int i = 0; i < studentList.size(); i++)
{
if (studentList.get(i).getEmail().contains("#") && studentList.get(i).getEmail().contains(".") && !studentList.get(i).getEmail().contains(" "))
{
System.out.println("Scanning Roster");
}
else
{
System.out.println("Invalid email address, " + studentList.get(i).getEmail());
}
}
}
This what I have done so far, even though I check all of them I get AlertDialog message.
private void validateCheckBoxes() {
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
&& ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
} else {
AlertDialog.Builder facilitiesError = new AlertDialog.Builder(AddStation.this);
facilitiesError.setTitle("Station Facilities are not selected");
facilitiesError.setMessage("Please select at least one facility ");
facilitiesError.setNegativeButton("OK", null);
facilitiesError.create().show();
}
}
By "selected" do you mean "checked"?
if (toilets.isChecked() || wifi.isChecked() || trolleys.isChecked() || lifts.isChecked()
|| ticketMachine.isChecked() || stepFree.isChecked()) {
saveRecordsToDatabase();
}
modify your code:
if (toilets.isSelected() || wifi.isSelected() || trolleys.isSelected() || lifts.isSelected()
|| ticketMachine.isSelected() || stepFree.isSelected()) {
saveRecordsToDatabase();
}
Explanation: you are using all && operators in if statement, which means you get alert message only if all the check boxes are checked.
If you use all || (or) operator, it means you get alert message if at least one checkbox is checked.
I'm trying to make sure that the first character the user enters in this textbox is a letter. If it isn't, however, there will be a message box pop-up notifying the user that the first character cannot be a number, and must be a number. The problem is that the program completely ignores the code after the event occurs to check and see if there is a letter in the first position.
if (event.getSource() == item2)
{
string = String.format("Account number: %s", event.getActionCommand());
str = string.substring(1);
try{
Integer.parseInt(string.substring(0,1));
parsable = true;
}catch(NumberFormatException e){
parsable = false;
}
if(parsable == true)
{
JOptionPane.showMessageDialog(null, "ENTER THE LETTER CORRESPONDING WITH YOUR ACCOUNT NUMBER AS THE FIRST CHARACTER IN THE TEXT FIELD.");
}
/*
try
{
Integer.parseInt(str);
}
catch(NumberFormatException e)
{
String.format("enter a valid number");
}
*/
}
Any help is appreciated.
because you are using String.format("Account.... your string's first character will always be 'A' of Account you have to check on String which you recived from event.getActionCommand() mathod
Here is my code:
public static void nameset(){
int no = 1;
name = JOptionPane.showInputDialog(frame, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name.equals("") || name.equals(JOptionPane.CANCEL_OPTION));{
JOptionPane.showMessageDialog(frame,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name.equals("") || name.equals(JOptionPane.CANCEL_OPTION)){
if (no == 2){
JOptionPane.showMessageDialog(frame, "Seriously? Again?! that's it..");
if (name.equals(JOptionPane.CANCEL_OPTION)){
System.exit(0);
}else{
System.exit(0);
}
}
}
}
I want it so if you press the cancel option it tell you to restart. But if you press cancel, it shows an error in the console. I think it's the name.equals(JOptionPane.CANCEL_OPTION), But I'm not sure. Is there any reason for it not to work? Thanks in advance for any help.
The cancel button will always result in null being returned. See official JavaDoc:
Returns: user's input, or null meaning the user canceled the input
So your condition should be changed to:
if(name == null || name.equals(""))
and you also need to remove the semicolon after your first if statement! Otherwise the following block will always be executed.
Once that's fixed, your "exit after 3 times no" will not work because you're not actually looping your input dialog.
Try this
int no = 1;
String name = JOptionPane.showInputDialog(null, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name == null || name.equals(""));{
JOptionPane.showMessageDialog(null,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name == null || name.equals("")){
if (no == 2){
JOptionPane.showMessageDialog(null, "Seriously? Again?! that's it.."+name);
if (name == null || name.equals("")){
System.exit(0);
}else{
System.exit(0);
}
}
}
I am writing a BMI calculator application. Currently an error happens which causes the program to stop working if I do not enter data into one field. For instance, there are two JTextFIelds for 'height', one being feet and the other inches. If I just input '6' into the feet JTextField and enter nothing into inches JTextField, then enter my weight in the weight JTextField and click on calculate, it does not work.
What I want to do is display a message dialog saying "Please make sure all fields are filled in" if one field does not contain data.
Below is the ActionHandler code that is added to my 'Calculate' button.
public void actionPerformed(ActionEvent e) {
double heightFT = ((Double.parseDouble(heightFt_TF.getText()));
double heightIn = (Double.parseDouble(heightIn_TF.getText()));
double weight = (Double.parseDouble(weight_TF.getText()));
double totalHeight = (heightFT*12) + heightIn;
BMI = (weight / (totalHeight*totalHeight)) * 703;
String s = BMI+"";
s = s.substring(0,4);
BMI_TF.setText(s);
}
Solved
I have now fixed the problem. What I did was add 'throws NumberFormatException' in the method and did a try catch. In the try code block I wrote the code I want to execute if all data fields are entered. In the catch clause I wrote code that uses the NumberFormatException and simply displays the message dialog with the error message. Now, if one field is not entered, the message dialog appears!
Just check if your JTextField objects contain text.
E.g:
if (heightFt_TF.getText() == null || heightIn_TF.getText() == null || weight_TF.getText() == null) {
JOptionPane.showMessageDialog(null, "Please make sure all fields are filled in");
}
Of course you also have to make sure, that the content of the textfields really contains a number.
Download Apache Commons Lang library and use StringUtils.isBlank(myTextField.getText()); to validate your fields.
public boolean validateFields() {
if (StringUtils.isBlank(heightFt_TF.getText()) {
// show message
return false;
}
if (StringUtils.isBlank(weight_TF.getText()) {
// show message
return false;
}
return true;
}
Only run your calculation if validateFields() returns true.
public boolean validate(JTextField field) {
boolean result = field.getText() != null;
if (result) {
try {
Double.parseDouble(field.getText()));
} catch(NumberFormatException e) {
result = false
}
}
return result;
}