asp.net mvc 3 validation summary not showing via unobtrusive validation - asp.net-mvc-3

I'm having problems getting the asp.net MVC client-side validation to work how I want it.
I have it basically working, however, the validation summary is not displayed until the user clicks the submit button, even though the individual inputs are being highlighted as invalid as the user tabs/clicks etc their way through the form. This is all happening client-side.
I would have thought the that the validation summary would be displayed as soon as an input field was discovered that was invalid.
Is this behaviour by design? Is there any way around it, as I would like the validation summary to be displayed as soon as it is discovered that one of the input fields is invalid.
My code is basically,
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
...
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
#Html.EditorFor(model => model);
...
And my _Layout.cshtml references jquery-1.4.4.min.js.

I used a version of Torbjörn Nomells answer
Except here I hang resetSummary off the validator object
$.validator.prototype.resetSummary= function () {
var form = $(this.currentForm);
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};
Then change calling it to
$.validator.setDefaults({
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length) {
$(this.currentForm).triggerHandler("invalid-form", [this]);
} else {
this.resetSummary();
}
}
});

You can setup the validation summary to be triggered a lot more often, in onready:
var validator = $('form').data('validator');
validator.settings.showErrors = function (map, errors) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length)
$(this.currentForm).triggerHandler("invalid-form", [this]);
else
$(this.currentForm).resetSummary();
}
}
Here's the resetSummary used above:
jQuery.fn.resetSummary = function () {
var form = this.is('form') ? this : this.closest('form');
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};

I have a similar question open here: How to display MVC 3 client side validation results in validation summary but the suggested solution by Darin does not seem to work the way I (and probably you) want it to.

Related

Multiple CheckBox Validation using spring JS?

I am creating dynamic Check Boxes in runtime. my requirement is have to validate atleast one checkbox checked or not. am doing this using springJS. But to validate i have to pass checkBox Id to spring Validation, But this ID array creating in runtime. how can i achieve this? i tried all solutions but it did'nt worked for me. i am doing like this it was working if i hardcode checkbox id.
<script type="text/javascript">
Spring.addDecoration(
new Spring.ElementDecoration({
elementId: '_CheckBox_ids',
widgetType: 'dijit.form.CheckBox',
widgetModule: 'dijit.form.CheckBox',
validate: function () {
if (dojo.query("#roo_apiUser_profile > input[type=checkbox]", 'dijit.form').filter(function (n) {
return n.checked;
}).length > 0) {
return true;
} else {
alert('choose at least one profile');
return false;
}
},
widgetAttrs: {
required: true
}
}));
</script>
You may add the onsubmit attribute in your form tag and call a function that does the validation on checkboxes.
Alternately, you may create your own extension of AbstractElementDecoration (defined in spring.js) using dojo.declare and pass to the validate attribute a function that will do the checkboxes validation for you. For elementId you may pass in the id of a div element that contains all the checkboxes. Spring.ValidateAllDecoration calls Spring.validateAll function. Make sure you do the necessary tweaking in your AbstractElementDecoration extension so that there is no exceptions in Spring.validateAll.

Ember event in one view update another?

I have a small extract from my Ember app here. My page contains a number of views each containing different data each with their own controllers.
I want a search field (in index view) to go in one view which should "talk" to the stationList controller to update the content of the stationList view. This doesn't work. I get an error: TypeError: this.get(...).search is not a function
The logging outputs the name of the contoller I've asked it to use: App.StationListController
I added a second search form inside on the StationList View. This one works just fine. The logging this time outputs a dump of the StationListController object. So I am guessing that the other search form, despite my code (in SearchFormView): controllerBinding : 'App.StationListController', is not correctly setting the controller.
So I guess my question is why not?
How can I route the change on the form field in the one view to call a funciton on another view's controller?
Here's my code:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<div id="searchForm">search form view search:
{{#view App.SearchFormView}}
{{view App.StationSearchField}}
{{/view}}
</div>
<div id="stationList">{{render stationList}}</div>
</script>
<script type="text/x-handlebars" data-template-name="stationList">
station list view search: {{view App.StationSearchField}}
<ul>
<li>List</li>
<li>will</li>
<li>go</li>
<li>here</li>
</ul>
{{searchTerm}}
</script>
And
App = Ember.Application.create({})
App.SearchFormView = Ember.View.extend({
init : function()
{
console.log("SearchFormView init", this.get('controller'))
}
})
App.StationSearchField = Ember.TextField.extend({
keyUp: function(event) {
var searchTerm = this.value
console.log("value",searchTerm,this.get('controller'))
this.get('controller').search(searchTerm)
}
})
App.StationListController = Ember.ArrayController.extend({
content : [],
searchTerm : null,
search : function(term)
{
this.set("searchTerm",term)
console.log("searching",term)
}
});
Fiddle: http://jsfiddle.net/ianbale/8QbrK/14/
I think the controllerBinding stuff is from the older version, I don't think that works anymore.
You can use controllerFor on get('controller') in the StationSearchField.
this.get('controller').controllerFor('station_list').search(searchTerm)
But controllerFor is deprecated and may be removed. Depending on your application structure you use needs on the controller.
Another way which I am using, is to send a custom event from the View, which the Route then sends to the corresponding controller.
App.IndexRoute = Ember.Route.extend({
events: {
search: function(term) {
controller = this.controllerFor('station_list')
controller.search(term);
}
}
});
and dispatch a search event from view like so.
this.get('controller').send('search', searchTerm);
The advantage of this method is you dispatch the same event from multiple places and it would get handled in the same way.
Here's the updated jsfiddle.

Fanycbox 1.3.4 ajax issue with ASP.NET MVC

I'm using Fancybox 1.3.4 with ASP.NET MVC 3.
I have following link :
<a id="various" href="Like/List/#feed.Id" class="petlikeCount liked">#feed.LikeCount</a>
and also jquery :
<script type="text/javascript">
$(document).ready(function () {
$("#various").fancybox({
type: 'ajax'
});
});
</script>
Controller action in Like controller :
public JsonResult List(int id)
{
return Json("success", JsonRequestBehavior.AllowGet);
}
My problem is that Like/List is never called (checked with the breakpoint) and fancybox just appears and show content of "parent" page....
I also tried with iframe content returning pure html back, but I'm getting same strange behavior as above.
Thank you in advance!
I'd recommend you using HTML helpers instead of hardcoding anchors:
#Html.ActionLink(
feed.LikeCount,
"List",
"Like",
new { id = feed.Id },
new { id = "various", #class = "petlikeCount liked" }
)
Another thing that you should make sure is that the feed.Id is actually an integer variable so that when the List action is invoked it is correctly passed this id.
So your url should look something like this: /List/Like/123. And then assuming tat you have kept the default route and haven't messed up with some custom routes, the List action should be called and passed the correct id as argument.
Also I would very strongly recommend you using a javascript debugging tool in your browser such as FireBug in which you will be able to see any potential errors with your scripts as well as the actual AJAX requests being sent which will allow you to more easily debug such problems.

MVC Custom Client side validation

In my mvc 3 application, I would like to execute a function when the user tries to submit the form. Within that function I will check a number of fields to determine if the user has provided the necessary data before submission.
How can I hookup a script to be executed when the user tries to submit the form?
(within the custom validate function, I need to check if various checkboxes have been selected and if yes, then additional values are selected from dropdownlists etc.)
How can I hookup a script to be executed when the user tries to submit the form?
You could subscribe to the .submit event of the form and after calling the standard client side validation call your custom function:
$(function() {
$('form').submit(function() {
if (!$(this).valid()) {
// standard client validation failed => prevent submission
return false;
}
// at this stage client validation has passed. Here you could call your
// function and return true/false depending on the result of your
// custom function
});
});
Another possibility is to write custom validation attributes and hook up a custom adapter as shown in this answer and a similar one.
$('#formId').submit(function () {
var standardIsValid = $(this).validate().form();
var customIsValid = customValidations();
if (!standardIsValid || !customIsValid) {
return false;
}
});
In the view (RAZOR or ASPX), you will define a script like you would in html, and in there will be your client-side validation.
For example :
<script>
//define your script here, ie. $.(#tagtovaildate).validate();
</script>
<html>
//code
</html>

MVC Form Validation

I am having trouble with my form validation. I have a form class with the Required attribute on it and I have ClientValidationEnabled to true in my web.config. I also have this call on my page #{Html.EnableClientValidation();}
I am using ajax form with the before submit option to catch the validation. Here is what I have:
$(document).ready(function () {
var options = {
beforeSubmit: ensureValid
};
$('#applyForm').ajaxForm(options);
});
function ensureValid(formData, jqForm, options) {
var result = $('#applyForm').validate();
console.log(result.valid());
return result.valid();
}
The code hits the ensureValid function but keeps continuing to the action in the controller even when I know a property should fire.
Thank you for any insight,
Brenna
If you are using asp.net-mvc-3, I would recommend at looking at using jquery.validate to perform your validation. It's far easier to setup, and generates cleaner code. You can see how to set this up in my blog post (I also cover a possible problem you could run into).

Resources