ValidationMessageFor display outside the form - asp.net-mvc

I have this validation message for a field in MVC view outside the begin form. However it is not displaying that.
#Html.ValidationMessageFor(m => m.OldPassword)
Is there any possible way I can achieve this? Since I don't wanna use a Jquery or Javascript function just to validate this.

Keep the validation message inside the form with a Div tag.
Make the Div display none.
On button click, check the IsValid property of the form
If in valid, then copy the HTML() of the Div and put it into another div which will be outside the form.
Its not a clean solution, but the trick will work

ValidationMessageFor only works if the fields / Controls are inside the form post action for that controller. Otherwise need to do separate methods like JavaScript / Ajax / ViewBag to get the error.

It only works if #Html.ValidationMessageFor(m => m.Property) is inside the form. However, I managed to find a workaround that also updates the outside div when there are element changes, i.e., when the error messages change without re-submitting the form:
Place a <div id="outside-form"></div> outside your form.
Place a <div id="inside-form" style="display:none;"></div> inside your form, which contains all #Html.ValidationMessageFor(m => m.Property) statements.
This is the nasty part, in your jquery.validate.js, find the following:
form: function() {.....} and just before the function return add $("#outside-form").html($("#inside-form").html());. This ensures that your outside-div will be updated every time the whole form is validated.
element: function( element ) {.....} and just before the function return add $("#outside-form").html($("#inside-form").html());. This ensures that your outside-div will be updated every time each form element is validated.
That's it! I was wondering if there's some way of extending the form and element objects without changing the .js file itself.. do you have any clue about this?

Related

Struts 2 - Tiles-Result with HTML Anchor

is it somehow possible to add an anchor (or hash) to a Struts 2 Action-URL? To be specific:
I have a html form which can be extended with more fields if the user clicks a button "add more fields". This Button sends a html submit to the backend (Action "thismyaction") where a list object is filled with another set of input fields. The action then returns to a tile "thisismyform" which loads the same jsp as before, where the new fieldset is visible.
(Unfortunately there is no way to achieve that via ajax / JS in this project at the time. I know that you usually add fields that way, but i got the project as it is.)
Each fieldset is counted (fieldset-0, if user adds more fields another set is added "fieldset-1"). The sets always contain the same fields, but enumerated.
What happens here? There is a post to the action which generates another fieldset and redirects back to the same page, where it renders all fieldsets. Important: the result type is "tiles"! I guess this is what makes it difficult.
Now I want to dynamically add an anchor to this URL "thisismyaction.do", like e.g. "thisismyaction.do#fieldset-1". Use Case: User adds another fieldset, post to the action => result type="tiles" => JSP, user sees reload of the page with the new, second fieldset and gets "scrolled" to the second fieldset via the anchor. Is that possible?
I hope I could describe it properly, what I want to achieve... If there are questions, feel free to ask.
Simplest way I can think of right away is
<script type="text/javascript">
window.location.hash = "fieldset-<s:text name="latestIdOfFieldSet" />";
</script>
If you can figure out what's gonna be latestIdOfFieldSet before you render your jsp and set it in your action method. you should get what you are trying to do.

How to make form elements read only in GSP?

Hi i have a form in GSP and I want to make all the form elements read only after submit.
Is there any way to do it. I have form elements like textboxes, dropdowns attachment field......
I am using G:Form
I am also using java script in my GSP.
Please help me out
Thanks.
Keep in mind that even if you set the tags as readonly on the server side, users can still change them through a variety of means, and whatever the value on the form is before it gets sent back to you.
You can use an onsubmit event in the form tag, calling a JavaScript function which will disable any form elements you want to affect. Since GSP is server pages, not the browser, it will not normally be able to help you in this respect.
Certainly the easiest way is client-side with jQuery:
$(function() {
$('input, select, textarea').attr('disabled', 'disabled');
});

How to check if a <div> is valid with unobtrusive javascript

I have a form which loads a div on client side. I have hard coded textbox controls with all validation attributes, similar to what it renders when loaded from server. Inside the div there is submit button, but when I click on submit all validations messages on the form are displayed. I just need only the div elements validation messages to be shown. Telerik Grid control in ajax mode, does similar thing, i.e., appends textboxes with hardcoded validation attributes on client side, but it manages to fire validations only for the grid not entire form. I think I am missing something here.
$('#div').valid() --> doesn't work
$('#form').valid() --> works
You need to parse the validation rules of the containing form once you add the div to the DOM:
var form = $('#div').closest('form');
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
and here's a live demo.

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>

How to get the foreign key column data when it is used in a select box

I have this ruby on rails code
<%= builder.select(:serving_size_id, '') %>
I have not specified any options on purpose because I set the options in a different way when the page loads (using jQuery and Ajax).
The question: Is there any way I can get the value from the column "serving_size_id" but not change that line? I have a partial which I use it for new and edit and I think it would be sweet if I can do the setting of the selected index in JS.
Any ideas?
I'm not sure I completely understand your question, but if you want to set the value of the select field with JavaScript, you need to obtain the value in JavaScript at some point. I can think of two ways of doing this:
1) When you get the options via AJAX, have the server indicate which one is selected. This can be done by returning HTML <option> tags with selected="selected" set for one of them. To do this, your AJAX request is going to have to provide information about the object this select field is for (so the server can look up the object's current serving_size_id value).
2) When you render the field in your original partial, also render some JavaScript which sets the current value of the field, for example, underneath what you have above:
<%= javascript_tag "var ssid = '#{builder.object.serving_size_id}';" %>
Then, after the options are retrived via AJAX, the ssid variable is checked and the correct option is selected.
using jQuery in rails is easy but a little more difficult than prototype.
ex: "div id="serving_size" class="nice" rel="<%=h num%>">Stuff Goes Here.../div>"
in application.js do the following:
//application.js
$(document).ready(function(){
if($('#serving_size'){
$('#serving_size').live("mouseover",function(){
//we are hovering over specific div id serving size
if($('#serving_size').hasAttr('rel')){
alert($('#serving_size').attr('rel'); //your dynamic rel value, and fire function
}
}
}
if('.nice'){
$('.nice').live("mouseover",function(){
//we are now hovering over any item on page with class nice
if($(this).hasAttr('rel')){
//we are now using jQuery object ref and finding if that obj has attr rel
alert($(this).attr('rel')); // shows dynamic rel value
}
}
}
});
If you use the above code you should be able to do anything you want and fire any custom code from each of your set event callbacks.
The 'live' function in jQuery is great because it can be called on items that will eventually be on the page (eg. if you fill in something with ajax, jQuery will be prepared for that item being in the page)
I hope this help.

Resources