MVC Custom Client side validation - asp.net-mvc-3

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>

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.

How to use JQuery Custom Validators and onChange Event in <input type='file' /> using ASP.NET MVC 3

Invoking custom jquery validator within another javascript function
How to invoke jQuery Custom Validator for a <input type='file' /> on onChange Event within normal javascript function. I need to capture the event and trigger a custom validator already registered, inside it creates a table with rows corresponding to each file attempted to upload.
I have read this article but I can't validate what the author is saying: Version of Custom Validator Calling
Thanks in advance.
I have a piece of jquery custom validator function that makes the magic, it checks valid files extensions (images are the main target right now) when uploading them to the server:
$(document).ready(function () {
$('#UploadedFile').live('change', function () {
//TODO
alert('Hey hey!');//It works, because the event is captured and calls this line
return jQuery.validator.methods.extensions.call(null, $(this), null);//Doesn't work for me
//This is for running validation in the client-side
});
});
jQuery.validator.addMethod("extensions", function (value, element, params) {
var extensionsAllowed = params.extensions;
var pattern = new RegExp(extensionsAllowed);
var elementToValidate = $(element);
var maxUploadSize = Math.floor(5000000 / 1024) / 1024;//converting to Kilobytes
var result = fnCreateUploadDetailsTable(elementToValidate, pattern, maxUploadSize);
return result;
//It works for server-side Data Annotations validator,
//but the request travels over the HTTP connection and I want to avoid overloading the server
//with this basic function
});
jQuery.validator.unobtrusive.adapters.add("extensions", ["extensions"], function (options) {
options.rules["extensions"] = options.params;
options.messages["extensions"] = options.message;
});

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

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

Jquery Validation Plugin, dynamic form validation

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:
$('.dynamicForm').live('submit',function(){
$(this).validate();
if($(this).valid()){
if(!confirm('Are you sure?'))
e.preventDefault();
}
});
It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?
Somehow this seems to work:
$('.dynamicForm').live('mouseover',function(){
$(this).validate({
submitHandler:function(form){
if(confirm("Are you sure?")){
form.submit();
}
}
});
});
Use the submitHandler function available in the validate options:
$(".dynamicForm").validate({
submitHandler: function(form) { //Only runs when valid
if(confirm('Are you sure?'))
form.submit();
}
})
From the docs - submitHandler:
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Resources