Alert Message When TextField is empty (javafx) - javafx

I would like for my code to check if the textfields in my form are empty & then show a pop up alert message. My problem is, even if the textfields are filled in this alert message pops up as soon as I hit "ENTER" anyway. Any help is appreciated !
BtnEnter.setOnAction((ActionEvent e) -> {
if (txtfName.getText().isEmpty() | txtlName.getText().isEmpty() |
txtMI.getText().isEmpty() | txtStreeAdd.getText().isEmpty()
| txtCity.getText().isEmpty() | txtZip.getText().isEmpty()
| txtPhone.getText().isEmpty() | txtEmail.getText().isEmpty()
| txtSecEmail.getText().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText("The fields highlighted in red must be filled "
+ "out.\nPlease try again.");
alert.showAndWait();

I believe part of the issue may be using the single pipe | for OR instead of the standard ||.
However, there's another approach you could take that may be a little easier to read. This is how I handle validation in my applications:
public boolean validate() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (txtfName.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
}
if (txtlName.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
}
if (txtMI.getText().trim().isEmpty()) {
errors.append("- Please enter a middle initial.\n");
}
if (txtStreetAdd.getText().trim().isEmpty()) {
errors.append("- Please enter a street address.\n");
}
if (txtCity.getText().trim().isEmpty()) {
errors.append("- Please enter a city.\n");
}
if (txtZip.getText().trim().isEmpty()) {
errors.append("- Please enter a ZIP code.\n");
}
if (txtPhone.getText().trim().isEmpty()) {
errors.append("- Please enter a phone number.\n");
}
if (txtEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a primary email address.\n");
}
if (txtSecEmail.getText().trim().isEmpty()) {
errors.append("- Please enter a secondary email address.\n");
}
// If any missing information is found, show the error messages and return false
if (errors.length() > 0) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning");
alert.setHeaderText("Required Fields Empty");
alert.setContentText(errors.toString());
alert.showAndWait();
return false;
}
// No errors
return true;
}
This has the added benefit of letting the user know exactly what information is missing as well. With this, you simply call the validate() method when the user clicks the action button. If validate() comes back true, you know you have all the information needed.

You can also approach it in this another way without Alert alert = new Alert(Alert.AlertType.WARNING); Here is a piece of code:
public boolean validateForm() {
StringBuilder errors = new StringBuilder();
// Confirm mandatory fields are filled out
if (jTextField1.getText().trim().isEmpty()) {
errors.append("- Please enter a first name.\n");
jTextField1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField2.getText().trim().isEmpty()) {
errors.append("- Please enter a last name.\n");
jTextField2.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
String s = ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
if (s.equals("")) {
errors.append("- Please choose a date.\n");
jDateChooser1.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
if (jTextField3.getText().trim().isEmpty()) {
errors.append("- Please enter the age.\n");
jTextField3.requestFocusInWindow();
JOptionPane.showMessageDialog(null, errors, "Warning!", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
In this way, you can check if users know what exactly missing and show them an alert message. Add a listener for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(validateForm()) {
System.out.println("First name: "+jTextField1.getText());
System.out.println("Last name: "+jTextField2.getText());
System.out.println("Date: "+jDateChooser1.getDate());
System.out.println("Age: "+jTextField3.getText());
}
}

Related

Nested subscription to messages on xamarin forms

I'm new with Xamarin forms and don't know how to deal with this case. I've tryed to implement it in several ways but with no success.
I have a page where when user makes an action (write a text on a text box and send it with enter key) my app must make some checkings. Depending on the result of the checks, it could be necessary to show a modal page with a list of item to select. Ones user makes the selection process must continue with other checks. And here is my problem, because in this next checkings I have to show another page. User must make a selection/enter some date, and then continue to complete the proccess, but this page is not appear.
I'm using the messagingCenter to subscribe to the modal pages. First modal page appears and makes the selection well. Second modal page is never shown and then proccess never complets.
Here is some of my code:
NavigationPage navigationPage = new NavigationPage(new ListItemsPage(products));
Navigation.PushModalAsync(navigationPage);
MessagingCenter.Subscribe<ListItemsPage, Guid?>(this, "Select product", (obj, item) =>
{
try
{
if (item != null)
{
product = products.SingleOrDefault(x => x.Guid == item);
if (product != null) ProcessLine(product);
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
MessagingCenter.Unsubscribe<ListItemsPage, Guid?>(this, "Select product");
}
});
On ListItemsPage I have this code whe item is selected:
private void MenuItem_Clicked(object sender, EventArgs e)
{
// some logic...
Navigation.PopModalAsync();
MessagingCenter.Send(this, "Select product", SelectedGuid);
}
SelectedGuid is a Guid type data and when debbugin is well selected.
Problems comes when goes to ProcessLine method.
private void ProcessLine(Product product) {
// make some logic...
NavigationPage navigationPage = new NavigationPage(new ControlUnitsPage(model));
Navigation.PushModalAsync(navigationPage);
MessagingCenter.Subscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", (obj, item) =>
{
try
{
if (item != null)
{
_date = item.Date;
_code = item.Code;
_units = item.Units;
Save(productLine, product, _units, _date,_code);
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
MessagingCenter.Unsubscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code");
}
});
}
ControlUnitsPage has the same structure as the last one page. First makes a PopModalAsync and then sends the message sending an instance of ControlUnits type.
private void Button_Clicked(object sender, EventArgs e)
{
//some logic...
Item = new ControlUnits() { Date = DateField.Date, Code = CodeField.Text, Units = int.Parse(SelectedUnits.Value.ToString()) };
Navigation.PopModalAsync();
MessagingCenter.Send(this, "Select units, date and lot code", Item);
}
I think problem is in the order of invoking method but dont know what is the properly order because I am not able to understand how pushmodal, popmodal methods work, whether or not I should use await with it if after that comes a subscription. I really don't know and I need help, please.
Thank you so much!
your Send and Subscribe calls both need to use matching parameters
if Subscribe looks like this
MessagingCenter.Subscribe<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", (obj, item) => ... );
then Send needs to match
MessagingCenter.Send<ControlUnitsPage, ControlUnits>(this, "Select units, date and lot code", Item);

Put and Get Selected Radio Button from Radio Group using SharedPreferences

want to store selected radio from and radio group and once that fragment is again launch , previous selected radio should be selected , I tried but not able to get it .
I need to store selected position on Click of button only .
This is code which I am using :
radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1);
radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.radioButton1) {
Toast.makeText(getActivity(), "You: Dude !!!",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.radioButton2) {
Toast.makeText(getActivity(), "You: Babe !!!",
Toast.LENGTH_SHORT).show();
}
}
});
Try something like this
radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1);
radioButton1=(RadioButton) rootView.findViewById(R.id.radioButton1);
radioButton2=(RadioButton) rootView.findViewById(R.id.radioButton2);
SharedPreferences myPrefs=context.getSharedPreferences("general",context.MODE_PRIVATE); //you can give any name in place of general to your preferences
radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.radioButton1) {
Toast.makeText(getActivity(), "You: Dude !!!",
Toast.LENGTH_SHORT).show();
//save in preferences
myPrefs.edit().putInt("selected",1).commint();
} else if(checkedId == R.id.radioButton2) {
Toast.makeText(getActivity(), "You: Babe !!!",
Toast.LENGTH_SHORT).show();
//save in preferences
myPrefs.edit().putInt("selected",2).commit();
}
}
});
//check if there is any value in preferences and set accordingly
int s=myPrefs.getInt("selected",0); //will return 0 when nothing is stored
if(s==1){
radioButton1.setChecked(true);
} else if(s==2){
radioButton2.setChecked(true);
}
To add a value in preferences, you first use the edit() tag and then use putInt or putString ,etc. to add value to the preferences.
Example putInt("selected",1 ); Here the 'selected' is the key or name that you provide so that you can fetch the value with that key. And '1' is the value to be stored against that key.
Then use commit() to save the value in preferences.
When you need to fetch a value, you use getInt or getString etc. to fetch the value.
Example getInt("selected",0);. Here selected is the key whose value you want to fetch. 0 is the default value that will be supplied in case there is no value under the key that you have provided.
Hope this helps :)

Sitecore: Show input option after using menu context item

I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method.
In this method i create a new item ( template type and parent item are given in the source of the treelist field ).
All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this.
class MyTreeListEx : TreelistEx, IMessageHandler
{
void IMessageHandler.HandleMessage(Message message)
{
if (message == null)
{ return; }
if (message["id"] == null)
{ return; }
if (!message["id"].Equals(ID))
{ return; }
switch (message.Name)
{
case "treelist:edit":
// call default treelist code
case "mytreelistex:add":
// my own code to create a new item
}
}
}
Does anyone have any suggestions on how to achieve this ?
Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is SheerResponse.Input method.
You can use it like this:
using Sitecore.Configuration;
using Sitecore.Globalization;
using Sitecore.Shell.Applications.ContentEditor.FieldTypes;
using Sitecore.Web.UI.Sheer;
void IMessageHandler.HandleMessage(Message message)
{
...
case "mytreelistex:add":
Sitecore.Context.ClientPage.Start(this, "AddItem");
break;
}
protected static void AddItem(ClientPipelineArgs args)
{
if (args.IsPostBack)
{
if (!args.HasResult)
return;
string newItemName = args.Result;
// create new item here
// if you need refresh the page:
//SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");
}
else
{
SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation,
Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength);
args.WaitForPostBack();
}
}
This code will even validate your new item name for incorrect characters and length.

Asp.Net validation check at client side

I am validating data at client side in asp.net validator by using following code snipet.
function ValidateData(){
if (!Page_ClientValidate("Validator1") || !Page_ClientValidate("Validator2")) {
return false;
}
else{
return true;
}
I called it on submit of button. But it showing validation messages of Validator1 group. Its not showing me validation messages of Validator2 group.
Just gone through :
see this link question , here its told - || operator short-circuits if the left condition is true.
Does a javascript if statement with multiple conditions test all of them?
If you want both , then cant you try like this :
function ValidateData(){
if (!Page_ClientValidate("Validator1"))
{
if (!Page_ClientValidate("Validator2"))
{
return false;
}
else
{
return false;
}
return false;
}
else
{
return true;
}
}
Just a random try , this code :)
Rigin

Using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. If condition is not working properly

If condition is not working properly. I have some set of user id to login to my application, using webdriver, I am able to run successfully for the first user & for next user it is failing at if condition. Please find the code below and it has to check the more if conditions to run successfully.
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
{
driver.findElement(By.id("ctl00_Header_Lbtn_Logout")).click();
msg ="Valid User Login";
System.out.println(msg);
}
else
if(driver.getTitle().contains("700Dealers Inc."))
{
driver.findElement(By.xpath("//table[#id='lgnLogin']/tbody
/tr/td/table/tbody/tr[4]/td")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("Security Question And Answers"))
{
driver.findElement(By.xpath("//table[#id='Table_01']/tbody
/tr[5]/td/table/tbody/tr/td/table/tbody/tr/td/span/span[1]")).getText();
System.out.println(msg);
}
else
if(driver.getTitle().contains("700 credit Change Password"))
{
driver.findElement(By.xpath("//div[#id='panelscreen']/table
/tbody/tr/th/span")).getText();
System.out.println(msg);
}
Please help me out in this issue. Help will be appreciated.
Thread.sleep(5000L); is probably the root of your problems.
So, you may want to replace that :
Thread.sleep(5000L);
if(driver.findElements(By.linkText("Logout")) != null)
with an explicit wait :
try {
WebElement logout = (new WebDriverWait(driver, 5))
.until(new ExpectedCondition<WebElement>(){
#Override
public WebElement apply(WebDriver d) {
return d.findElement(By.linkText("Logout"));
}});
//Logout found, do stuff
} catch(TimeoutException e) {
//No logout element, do stuff
}

Resources