MVC Form Validation - asp.net-mvc-3

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).

Related

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>

Magento ajax form validation

I have a form in Magento that I build in code, and that works with ajax, which I need to validate.
I would like to be able to use Magento's built-in validation functionality, but I don't know how I would trigger it since the form is not submitted. The data is retrieved via ajax and outputted in a list below the form.
Is there someone who can point me in the right direction?
Thanks in advance.
Edit:
This is the javascript code used to hande the ajax request. Its called by the onclick event of the button.
function advancedtranslateSearch(url){
new Ajax.Request(url, {
method: 'get',
parameters: $('search_form').serialize(),
onSuccess: function(transport) {
json = transport.responseText.evalJSON();
$('result').update('<div class="hor-scroll">'+json.records+'</div>');
}
});
}
You should use form's onsubmit event.
To prevent page from reloading you must return false value from your function.

get $.post to work with the validate plugin on multiple forms without seperate functions

On a fansite im doing http://yamikowebs.com/ee/
I have a few forms (2 atm). I used $.post to find out what form is being submited. submit the form and display that pages results where the form was originally with .html().
My next step was to use the validator which is working fine but im not sure how to put the 2 together.
submitHandler: function(form){} seems to be the setting for how its submitted. However, I can't get this to work with my $.post function or find out what form is being processed.
If I leave the defaults for validation plug-in if there no errors it will send you to the page. the ajax plug-in that it works with doesn't do what I want. Below is my $.post function
form validation:
//ajax post
$("form").submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent("div")
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
http://docs.jquery.com/Plugins/validation#source is the validation plugin
You're correct in thinking that submitHandler is the right callback to use. However, I ran into some interesting issues while using it with multiple forms (like you're trying to do). For example, in this code:
$("#form1, #form2").validate({
submitHandler: function(form) {
alert(form.action);
alert(form.id);
}
});
The submitHandler callback does not get supplied the correct parameter (it always gets #form1). I believe this is actually a bug in jQuery-validate (so I've filed it here).
Anyway, a decent workaround would be to wrap the validate call in .each():
$("form").each(function() {
$(this).validate({
submitHandler: function(form) {
/* 'form' has the correct value */
var values = $(form).serialize(),
$div = $(form).parent("div");
alert(form.action);
alert(form.id);
/* Perform AJAX call here */
}
});
});
Example: http://jsfiddle.net/andrewwhitaker/MmCXN/

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

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.

Resources