How to validate a single field with Hibernate Validator? - java

I'm looking for a way to validate a single field at a time. This is so, while a user is filling in a form, each time the keypress or blur event occurs for each field, i can validate that field individually and show / hide its error message.
Is that possible? If so, how can I do it? Some google searching hasn't turned up any results which validate a single field, rather than the whole form.

You can use javax.validation.Validator#validateProperty() for that purpose.

I'd recommend that you try using Javascript Regular Expressions to validate user inputs and show/hide error messages.
I provided a code implementation example in the post at this link: Example using Regular Expresssions
Add an event listener to relevant input field in the DOM to provide responsiveness.
var letterField = document.getElementById('letterField'); // DOM element containing user input
letterField.addEventListener('keyup', function() { // key press event listener using anonymous function
if (event.keyCode === 13) { // run this code if the 'enter' key is pressed
if ( ... ) {
...
};
};
};
If you want to add effects, include the following code to transition the error message. Refer to the jQuery API for other effects:
userInputError.delay(800).fadeOut();

Related

Wicket IFormValidator - Mark multiple FormComponents as invalid

I have an IFormValidator that checks if the values of multiple FormComponents are coherent.
Now if validation fails, I'd like to highlight all related FormComponents and respective HTML label tags, just like it happens with Validators, that are responsible for only a single FormComponent (e.g. StringValidator).
My first try was calling FormComponent#invalid() on all related FormComponents, but that doesn't seem to do the trick, since it just calls FormComponent#onInvalid(), which does nothing by default.
The second thing I tried was calling FormComponent#error(String) on each component but that of course generates an additional error message for each FormComponent, which is not the desired behaviour. But at least it does highlight the individual invalid FormComponents.
What would be the correct way to do this? Is there a simple way I'm overlooking, since the IFormValidator#getDependentFormComponents() method, which I'm supposed to implement, already tells the Validator, which FormComponents will be invalid as a result failing the validation?
Here is a stripped down example of what I tried with Wicket 8.3:
wicketForm.add(new IFormValidator() {
#Override
public FormComponent<?>[] getDependentFormComponents() {
return new FormComponent<?>[] {formComponent1, formComponent2, formComponent3};
}
#Override
public void validate(Form<?> form) {
if (/*values of formComponent1-3 are not coherent*/) {
form.error("<error message>");
/* No highlighting at all */
formComponent1.invalid();
formComponent2.invalid();
formComponent3.invalid();
/* Highlighting works, but obviously produces same error message multiple times */
formComponent1.error("<error message>");
formComponent2.error("<error message>");
formComponent3.error("<error message>");
}
}
}
);
A FormComponent is deemed as invalid only when its #error() methods are called - see org.apache.wicket.markup.html.form.FormComponent#isValid().
If you want to show only the error feedback message of the Form then you need to instantiate your FeedbackPanel as:
new FencedFeedbackPanel("id", new ComponentFeedbackMessageFilter(form));
This way it will render the feedback messages only of the Form.
You can use the feedback messages of the form components to show their specific errors next to the respective HTML form element (input, select, etc.)

JavaScript EJB variable field holding value?

I have an ajax enabled list of records that I'm going through and each one has a dropdown box that I'm trying to make a required field for the form to submit. To complicate matters the 'Close Record' button is not the submit button so I can't just use required attribute on the select(dropdown box) that I'm using. The value for the selected dropdown box is saved in an Enterprise Java Bean so I thought I could just write a JavaScript function to check the value:
function CheckForm() {
var clearObj = document.getElementById("mySelect");
if(clearObj.value != "") {
return true;
} else {
clearObj.style.backgroundColor ='yellow';
}
return false;
}
This doesn't work because once I close one and go to the next it's maintaining the value of the previous record on the page. Basically I have an update-content event that I need to know how to handle. Any ideas as to how to manipulate the DOM or JSON object to make this select a required field? Thanks.
With the little information given, I would assume that when you close the existing record and then loading the next record, you are doing it through an ajax request. If thats the case, then you can add a call back for the ajax request, which would reset the drop down.
This should be a comment, but as you see, I dont have 50 points :-)

Struts 1.1: ActionErrors between different Actions

I have a form (form.jsp) and a connected FormAction ActionA. ActionA does validations and stores ActionErrors and the form.jsp will print them using <html:errors../> tag.
All this is working fine.
I then wanted to add some on-the-fly server side validation on onblur event on one of the form fields (fieldA). I do this using jQuery's $.post. It goes to a different Action class (ActionB) which will return a value, that I can print in a div under fieldA. This also works fine.
The problem is to combine the two. I use saveErrors method in ActionA and need to reset it with the new errors I get in ActionB.
Example: If fieldA was value "A" and fieldB was "#$" and my ActionA returned errors "No capitals for fieldA" and "No symbols for fieldB" on pressing Submit, then when user changes fieldA to "123" and presses tab, the errors shown should be "No numbers for fieldA" and "No symbols for fieldB" i.e. first error gets removed.
But how do I access the errors, if it isn't in the request!
Ok I worked it out. I just used jQuery to make the entire div with the error (class="globalError") not show (display:none) and then added my new errors in a similar div under that.. so, it just looks like the errors section changes :-). Thanks for the help.

how to change the value of textfield + jQuery + Struts2

I have two textfield A , B : i want to do something like when i enter something in textfield A,this value will be use it in some action and result will be displayed in textfield B without clicking the submit button using ajax.
how can i do it please ? note that i am a using struts2
Most of the information has already been provided by #alexanderb and i believe that Jquery is good way to go, now lets come to the second half of your question about using AJAX in your code. there are few ways you can send results from your action class.
Return JSON from your action class and use above code.
Use stream result type in your S2 code and place the data in the textfield.
Still i believe JSON with Jquery is good way to go which not only provides you the feasibility to easily extend functionality in future but also provide a clean way.Struts2 provides a plugin which can convert the data being send from your action class to JSON and all you will be left to parse the JSON data in your UI to fill the text-box.For details how to work with JSON in s2 refer to JSON plugin for detail
S2-json-plugin
With JSON plugin your flow will be
Call your Action class on specific event in text box.
Configure your action to return JSON data using S2-JSon plugin.
Action will return JSON to the Jquery code.
Parse the JSON data and fill the text box with the value
It should be easy. Suppose you have action that takes value as string and return some string back, availble on '/app/service' url.
You can create such code for that:
$(function() {
$('#text_1').on('keyup', function() {
var value = $(this).val();
$.post('/app/service', JSON.stringify(value), function (r) {
$('text_1').text(r);
});
});
});

Bridge between the Java applet and the text input controls on the web page

I have been working with a Java applet which is an applet that helps to write using only a mouse. For my case, I am trying to incorporate this into my webiste project as follows:
When the user clicks on any input element (textbox/textarea) on the page, this JAVA applet loads on the webpage itself. In the screenshot of the JAVA applet seen below, the user points to an alphabet to and the corresponding text gets written in the text box of the applet.
Now what I am trying to do is to get this text from the TextBox of the applet to the input element on the webpage. I know that this needs an interaction between the Java and JavaScript, but not being a pro, I really do not have the catch. Here's the Java applet and the code I have written.
Java applet and jQuery code (298kB): http://bit.ly/jItN9m
Please could somebdoy help for extending this code.
Thanks a lot!
Update
I searched somewhere and found this -> To get the text inside of Java text box, a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In the JQuery code, the following lines are to be added I think:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
For the code of the applet, I saw a GNOME git page here. The getText call already exists -- look at the bottom of this file: http://git.gnome.org/browse/dasher/tree/java/dasher/applet/JDasherApplet.java
I'd need to call 'getCurrentEditBoxText' but when should this method 'getCurrentEditBoxText' be called?
In my case, I would probably have to do it when the user clicks in a new input control etc.
You can have full communication between your Applet and any javascript method on the page. Kyle has a good post demonstrating how the Javascript can call the applet and request the text value. However, I presume you want the HTML Textfield to update with each mouse click, meaning the applet needs to communicate with the page. I would modify your javascript to something like this:
var activeTextArea = null;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
});
function updateText(text) {
// Careful: I think textarea and input have different
// methods for setting the value. Check the
// jQuery documentation
$(activeTextArea).val(text);
}
Assuming you have the source for the applet, you can have it communicate with the above javascript function. Add this import:
import netscape.javascript.JSObject;
And then, in whatever onClick handler you have for the mouse clicks, add:
// After the Applet Text has been updated
JSObject win = null;
try {
win = (JSObject) JSObject.getWindow(Applet.this);
win.call("updateText", new Object[] { textBox.getText() });
} catch (Exception ex) {
// oops
}
That will update the text each time that chunk of code is called. If you do NOT have access to the applet source, things get trickier. You'd need to set some manner of javascript timeout that constantly reads the value from the applet, but this assumes the applet has such a method that returns the value of the textbox.
See Also: http://java.sun.com/products/plugin/1.3/docs/jsobject.html
Update Modifying the applet is your best shot since that is where any event would be triggered. For example, if you want the HTML TextField to change on every click, the click happens in the applet which would need to be modified to trigger the update, as described above. Without modifying the applet, I see two options. Option #1 uses a timer:
var timer;
var activeTextArea;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
updateText();
}
function updateText() {
// Same warnings about textarea vs. input
$(activeTextArea).val($('#appletId')[0].getCurrentEditBoxText());
timer = setTimeout("updateText()", 50);
}
function stopUpdating() {
clearTimeout(timer);
}
This is similar to the code above except clicking on a text area triggers the looping function updateText() which will set the value of the HTML text field to the value of the Applet text field every 50ms. This will potentially introduce a minor delay between click and update, but it'll be small. You can increase the timer frequency, but that will add a performance drain. I don't see where you've 'hidden' the applet, but that same function should call stopUpdating so that we are no longer trying to contact a hidden applet.
Option #2 (not coded)
I would be to try and capture the click in the Applet as it bubbles through the HTML Dom. Then, you could skip the timer and put a click() behavior on the Applet container to do the same update. I'm not sure if such events bubble, though, so not sure if this would work. Even if it did, I'm not sure how compatible it would be across browsers.
Option #3
Third option is to not update the HTML text field on every click. This would simply be a combination of Kyle's and my posts above to set the value of the text field whenever you 'finish' with the applet.
Here's a possible solution. To get the text inside of your Java text box, write a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In your JQuery code, add the following lines:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
I found most of what I posted above here. Hope this helps.
This page explains how to manipulate DOM from a Java applet. To find the input element, simply call the document.getElementById(id) function with id of an id attribute of the text input box.

Categories