How to disable struts 2 validation before form submission? - struts2

I'm doing a project with struts2, Hibernate.
I want struts to validate my form. I have added a MyAction-validation.xml and it works fairly well. (I say fairly well because it doesn't validate on the client side. I have set the validate attribute of the <s:form/> tag to true)
First it provided me some errors and googling it I got that I should add a result with input name. So now I have a result with input name in my action without understanding well how it works and why.
My action returns a plain form when it is called by myAction.action url and when the form is submitted the data goes directly to the action parameters and saved in database. Then a filled form will be shown with a success message. The form fields should be validated upon the submission. But they are validated whenever the action is invoked. I tried #SkipValidation annotation but it cancels the validation completely. Even when I call the validate method in the execute method it doesn't run. I tested it by some System.out.println lines. My action definition in the struts.xml is the following:
<action name="ShowAddItemPage" class="action.clerk.ShowAddItemPage">
<result name="success" type="tiles">addItem</result>
<result name="generalError" type="tiles">clerkGeneralError</result>
<result name="input" type="tiles">addItem</result>
</action>
How can I make the validation work on the client side?
How can I make the validation run only upon the form submission and disable it when there form fields are provided by the application?
What is input result name for and why did I have to add it to the action results?

By setting the validate attribute to true, just like you said.
By having a different action for displaying the form, or by creatong an interceptor that skips validation on a GET (that's what I used to do), etc.
"input" is the result used when validation fails, although you can change it. If validation fails (and by default, type conversion failures as well) it has to go somewhere, and the "input" result is where.

Related

Struts2 Validatation

I have used Struts2 in a period time, but I am still very confused with Struts2 Validation.
I have used xml-validation, or method addFieldError() to validate, but when I first come to input form-page, a page with struts-tags, and a <s:form>, I can not just go to this page by a href-link, I must go through another action, I read that page jsp with struts-tags must come from a action.
And I usually create a Action just for redirect to this input page, in execute() method just "success" and the role of this action is to go to input page legally, and in action which process the input form input-page, I choose the "input" result is still this input page.
So, I feel uncomfortable to do this, I always have a GoToSiteAction, just first-time go to input page.
So, I really need your help!!.
Use the with input fields , create a action and create a validation xml file with same name as java file name
For example : AddInput.java
xml file: AddInput-validation.xml
put it in same package.
write all the validations you need for the form in xml file like this.
<field name="U_Id">
<field-validator type="requiredstring" short-circuit="true">
<message>Affiliate Id cannot be empty</message>
</field-validator>
</field>
<field name="Password">
<field-validator type="requiredstring" short-circuit="true">
<message>Password cannot be empty</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">30</param>
<message>Password cannot be less than 5 or more than 30</message>
</field-validator>
</field>
When you hit the action it will first hit the validation xml and check for the validation then process the action class part.
You are not using or not using the struts2-conventions plugin to it's full effect. Please see: http://struts.apache.org/2.1.6/docs/convention-plugin.html search this page for the string "Examples of Action and Result to Template mapping" and consider the table which follows.
In the future after adding the struts2-conventions-plugin jar to your project add the postfix "-input" to the end of all future forms.
Say we created a form to add a new employee:
/WEB-INF/content/add-employee-input.jsp
The struts2 form tag would reference an action simply called "add-employee" in a java class probably named something like com.mypackages.struts2.AddEmployee then if the add-employee action validation fails then "input" is returned and the "add-employee-input" form is again rendered. However we do not need to create a "add-employee-input" action, the conventions plugin will do this for us automatically... as such we can directly enter the form if we wish by referencing it and this is very convenient.
Try it out and you'll see what I mean.

Struts2 - See real destination url in browser on action result

In Struts2, when returning from a successful action, I want the user browser to show to the user the real url he is navigating into, and not the original call to action. As far as I understand, I cannot use a type="redirect" action because I need to pull the action results from the value stack.
Let's say, for example, if I define an action to save a new element in my db, and then I want to take the user to see the whole list of elements...:
<action name="doSavePage" class="FbPageAdmin" method="doSavePage" >
<result name="input">/pageadmin.jsp</result>
<result name="error">/pageadmin.jsp</result>
<result name="success">/pageList.jsp</result>
</action>
If the action finishes successfully, I want the user to see mysite.com/pageList.jsp, and not mysite.com/doSavePage.action
Is that possible?
Thanks everybody in advance!
Why would you want to have the JSP file name shown?
In any case, I'm not sure I understand; if you want to show a listing of objects after adding one, redirect to the "list" action (and/or method). You should do a redirect after a POST anyway (the post-redirect-get pattern) to avoid resubmitting the same form data on a refresh.
Also, ideally, JSPs should live under /WEB-INF to disallow direct aclient access.

Struts2 and form validation of prefilled forms

I'm using the validate() - method of struts2 to validate the form input. In my struts.xml I can define a result with name "input" which is displayed if the validation fails. This for the context :-)
Now my question: the form I want to validate contains a selectbox which is filled out of a database. The first time the form is displayed everything works fine. But if I validate the form and the "input" - result is displayed, I get an IOException because of the iterator which outputs the db-result into my selectbox. Is there a solution from struts2 or do I have to use a plugin or something like that? Thank you!
When validation fails, it's often necessary to "reload" data for the form page. There's a FAQ entry that covers repopulating controls after validation, mainly detailing the Preparable interface (preferred) and the use of the <s:action> tag (there are some subtle gotchas that can pop up with this, but in general, it's also okay).

Validation error messages are shown repeatedly in struts2

I m new to struts2. I am doing client side validation for my form. The error messages for validations that i wrote in properties file are repeated each time i submit.
e.g.
First submit
username required
Second submit
username required
username required
Please tell me how to clear previous error messages?
You should give example from your code. There is a document about Struts2 client side validation and about Ajax Validation there writes:
clearValidationErrors(formNode) : Removes validation errors from a form
so you can try to do it.
If you are using a table on ur jsp to display the form, then make sure that the table is a parent of the form tag. If the table is a child of form tag, the validation messages wont get cleared each time. Making the form tag as a child of table tag would solve your problem.
If you are using the spring integration you have to define your bean as scope="prototype", then you get a new instance of your Action for every request.
It's a good idea to do this for every Action.

ASP.NET MVC3 Custom Unobtrusive Client Side Validation not preventing Ajax form post

I have a "change password" page that needs to hash any passwords entered on the page via Javascript before sending. To complicate it, the page is loaded via a jQuery load() call, and is submitted by a jQuery.Form ajaxForm() call. Had everything working in MVC2, but MVC3 is giving me trouble.
That is, I have a page with a "Change Password" link that when clicked, loads the change password page into a jQuery modal popup, then the form on the change password page get's submitted via the jQuery.Form library (Essentially just wraps a $.ajax call), and returns it's result into the modal same modal popup.
Essentially, I have a model with two properties, OldPassword and NewPassword. I have two hidden fields generated by by view for these. They hold the hashed value of two other fields, PrehashOldPassword and PrehashNewPassword, and get updated via keyup events (I know, this means it does a whole SHA256 hash on every keyup... inefficient, but got the job doen for testing). The key here is that the regex validation and required field validation needs to be executed on these Prehash fields, which exist on the client side only (As obviously I don't want to transmit these fields to the server in any way).
So I manually create these two and add on the data-val-* attributes to the elements, i.e. they are NOT generated by the MVC helpers, etc. I am guessing that this is where I'm missing something. When the form submits with all fields empty, all of the errors popup that should, but the form goes right ahead and submits anyway.
==
So the things I've tried:
Yes, the unobtrusive library parse() method already get's called to parse the AJAX loaded form contents, and it appears to get all of the data validation stuff correctly, since I see the errors show up as fields blur(), and when I hit submit (before the ajax request completes and replaces the content of the popup).
Possible note: this call to the unobtrusive library's parse method happens AFTER the AJAX successfully loads the change password page into the popup... the AJAX form submit binding is put on document.ready of the loaded content, ergo, the AJAX form submission binding MAY be binding prior to, and thus firing before, the validation calls that the parse method may bind to the submit event...
However, (1) I am doing this same sort of thing in other places without issue, the ONLY DIFFERENCE being that I am manually putting these data-val-* attributes on elements I am creating manually! And (2), if I cause some kind of error on the OldPassword or NewPassword fields, i.e. a required field validation error by not loading a value into them, they display their error, and successfully STOP the form from submitting through the jQuery.Form method.
So I think something has to be wrong here:
<input id="PrehashNewPassword" type="password" name="PrehashNewPassword" data-val-required="The password field is required." data-val-regex-pattern="<%= RegexHelper.PasswordRegularExpression %>" data-val-regex="<%= RegexHelper.PasswordRegularExpressionError %>" data-val="true" />
I know that jquery.validate is getting the rules right, since I DO see the errors. It's just not stopping the form from submitting when their is an error in these manually generated elements, unless I do something like this, and add a pre-submit callback on the form's AJAX submission:
$("#ChangePasswordForm").ajaxForm({
beforeSubmit: function () { if (!$('#ChangePasswordForm').valid()) { return false; } },
target: '#overlay'
});
While this works, it is kind of ugly and I believe it causes the validation to be called twice... Not a huge deal, but less than ideal. So is there some other call that I need to make in the unobtrusive library to bind these?
Not sure if you found the problem, but you may try to
return false
in there if the form is not valid...
.
.
.
if (!$('form').valid()) {
return false;
}
// JSON POST...
.
.
.
If that doesn't work, then you could try to use:
$.validator.unobtrusive.parse($("#dynamicData"));
after dynamically adding your custom inputs. "dynamicData" is the ID of an element wrapped around the form
above found from here: http://weblogs.asp.net/imranbaloch/archive/2011/03/05/unobtrusive-client-side-validation-with-dynamic-contents-in-asp-net-mvc.aspx
Out of interest, what happens if you just get the form to validate?
<script type="text/javascript">
$("form").submit(function (evt) {
// validate here should trigger invalid fields
$('form').valid();
// JSON POST...
// stop form submitting
evt.preventDefault();
});
</script>

Resources