I have been assigned to a MVC3 project recently where i need to add client side validation to all of it's pages.
unfortunately this project has many pages which don't have any form on it in entire page hierarchy of a given view(from layout till deepest partial view), though i know it's wrong and that jquery validation and so unobtrusive both need fields to validated to be kept inside form,
but my hands are tied here as this project is running project since last 2 years and now entering into validation support part, and so none of senior technical stakeholders(managers and architects) are NOW ready to add forms to all pages missing it,
so here comes the question:
Can i validate a view or part of it (just a div) without having form? if yes, even if with workarounds, then how?. please share your thoughts.
Details on my search on matter:
I have searched for quite good time in SO and found few links having suggestion made saying it can be done, one such link is:
jQuery validation without "form" tag
based on all suggestion i could see, all from SO, i have created 2 fiddles:
one having form - http://jsfiddle.net/here4fiddle/r2w2u/4/ (validates and can see error)
other without it. http://jsfiddle.net/here4fiddle/r2w2u/5/
here this second fiddle, has 3 approaches(1.1 & 1.2 almost same, and 2), but none of those when uncomented and run, will show that validations fails, all say validation passed (isValid=true) though input field being blank(note in second fiddle there is no form on page as i want solution for without form scenarios).
Please correct any of approach in second fiddle(if it can work with changes) else if have some other suggestion which may work, please share.
code for second fiddle:
html:
Show error
javacsript:
function validate(e) {
var isValid = true;
var $divToCheck = $("#divToCheck");
//======================================
//aproach-1.1
/*
var abc = $("<form>").append($divToCheck).validate();
alert(abc);
alert(abc.valid());
alert(abc.errorList.length);
*/
//======================================
//approach-1.2 - start
isValid = $("<form>").append($divToCheck).valid();
alert(isValid);
//approach-1.2 - end
//======================================
//approach 2 - start
/*
jQuery('#divToCheck').wrap('<form id="temp_form_id" />');
isValid = jQuery('#temp_form_id').valid();
jQuery('#divToCheck').unwrap();
if (isValid) {
alert('no errors');
}
else{
alert('error');
}
*/
//approach 2 - end
//======================================
}
$(document).ready(function () {
$("#validate").click(validate);
});