ASP.NET MVC 3 RC 2 client side validation with globalization - asp.net-mvc

My goal is to validate a user input on the client-side, depending on the users' culture.
I have a primitive data-model with the following structure:
public class User
{
public int UserId { get; set; }
[Required]
[StringLength(20,MinimumLength=3)]
public string Name { get; set; }
[Required]
public double Height { get; set; }
}
Furthermore, I want to have client-side validation enabled, checking if it is a valid number. Therefore, I've added the following lines in the <head> section of my _Layout.cshtml.
<script src="#Url.Content("~/Scripts/jQuery-1.4.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Since I want to have the ability to validate the input in another language formats (in this particular context it's German with the decimal number format of 0,75 whereas in the US it would be 0.75), I've added the following lines (jQuery Globalization PlugIn) AFTER the previously mentioned jquery.validate.min.js and jquery.validate.unobtrusive.min.js.
<script src="#Url.Content("~/Scripts/jquery.glob.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/globinfo/jquery.glob.de-de.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.culture = jQuery.cultures['de-DE'];
$.preferCulture($.culture.name);
});
</script>
In addition, I've added the following line to the web.config in the system.web section just to make sure that the German culture is always selected:
<globalization culture="de-DE" uiCulture="de-DE" />
Now I am experiencing the following behavior:
If I type in 0,1 (note the German 'spelling') in the textbox for the value of "Height", the validation error message The field Height must be a number appears and I'm not able to submit the form.
If I type in 0.1 (English 'spelling'), I can submit the form but the server-side validation returns the following validation error message The value '0.1' is not valid for Height.
So now I am in some kind of dead lock where I can't get out.
Again, my goal is to validate the decimal number input on the client AND server side, based on the users' culture (in this case it's forced to be German). What am I doing wrong?
Any help is highly appreciated! Thank you in advance!

Unfortunately there's a naming conflict between jQuery.validate.format and jQuery.Globalization.format functions. Therefore you'll have to change your code to use the non-jquery Globalization plugin.
I just wrote a blog post about it here.
For you it should look like this:
<script src="#Url.Content("~/Scripts/globalization.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/globinfo/Globalization.de-DE.js")" type="text/javascript"></script>
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
if (!isNaN(Globalization.parseFloat(value))) {
return true;
}
return false;
}
$(document).ready(function () {
$.culture = jQuery.cultures['de-DE'];
$.preferCulture($.culture.name);
Globalization.preferCulture($.culture.name);
});
</script>
That should be enough.

I had to disable the UnobtrusiveJavaScript. The page does not react instantly anymore, but at least it works.
You can disable by default in the Web.Config.
<appSettings>
<add key="enableSimpleMembership" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="false"/>
</appSettings>
And I use the Microsoft scripts for validation:
MicrosoftAjax.js
MicrosoftMvcAjax.js
MicrosoftMvcValidation.js
And also the jquery-1.4.4.min.js & jquery.glob thing, but I think I use them internally. The validation is being done by the MS scripts.

Related

ASP.Net: Do I need to add javascript source of _ValidationScriptsPartial.cshtml to _layout.cshtml?

In ASP.Net 5 project I have a file named _ValidationScriptsPartial.cshtml by default:
<environment names="Development">
<script src="~/lib/jquery-validation/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment names="Staging,Production">
<script src="//ajax.aspnetcdn.com/ajax/jquery.validation/1.11.1/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
asp-fallback-test="window.jquery && window.jquery.validator">
</script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jquery && window.jquery.validator && window.jquery.validator.unobtrusive">
</script>
</environment>
But when I need to use jquery validation, I have to add:
<script src="~/lib/jquery-validation/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
below part of _layout.cshtml:
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/lib/hammer.js/hammer.js"></script>
<script src="~/lib/bootstrap-touch-carousel/dist/js/bootstrap-touch-carousel.js">
I HAVE TO ADD SCRIPT FOR JQUERY VALIDATION HERE
</script>
</environment>
What is the purpose of _ValidationScriptsPartial.cshtml?
How is this file used in the project?
Please give me reference how to use this file?
Partial Views are meant to be used inside other views. You would not normally add the validation scripts to the _layout.cshtml since that (_layout.cshtm) is used on every page.
However, if you have a view where you need to use these scripts you just add the partial view inside the .cshtml file of your view like this:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
If you created a standard web project with identity using VS 2015 then you can see an example of this usage in Views/Account/Register.cshtml
For example: you have a form with one of the field "Required" validation. You submit the form.
Case 1 : when _ValidationScriptsPartial is NOT used in the cshtml page
The validation will happen but it will check if ModelState is valid or not, everytime you submit the form.
Case 2 : when _ValidationScriptsPartial is NOT used in the cshtml page
The validation will happen but it will be a client side validation and it will not perform any of the tasks in the controller or relevant method, until and unless you resolve all validation issues.
To use the file in a cshtml page,
#section Scripts
{
<partial name="_ValidationScriptsPartial" />
}

Jaydata and Odata- HTTP Request Failed

I have my own custom server to expose data from an XML file. I can browse through it in whichever browser of my choosing and I can query the data in Fiddler, but Jaydata (or one of its building blocks) can't seem to grab the same data. What's most frustrating is that my code is (or was, I've tweaked it slightly to try and resolve these errors) pretty much an exact duplicate of code found here and here. Here's my script:
<script type="text/javascript" src="/Scripts/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/Scripts/datajs-1.0.3.js"></script>
<script type="text/javascript" src="/Scripts/jaydata.js"></script>
<script type="text/javascript" src="/Scripts/jaydataproviders/oDataProvider.js"></script>
<script type="text/javascript" src="/Scripts/Block.js"></script>
<script type="text/javascript">
var Context = new foo({
name: 'oData',
oDataServiceHost: 'http://localhost:xxx'
});
function createItemLI(user, id, css) {
var li = "<li></li>".append(name).addClass(css).data('id', id);
return li;
}
$.when($.ready, Context.onReady()).then(function () {
Context.Roots.toArray(function (roots) {
roots.forEach(function (root) {
$('#roots').append(
createItemLI(root.User, root.ID, 'root'));
});
});
});
</script>
Block.js, is the file generated by JaySvcUtil.exe
There's only one thing in the body of the .htm file, a simple <ul id="roots"></ul>
When I try to run the project, there's nothing on the page. When I used FireBug, I get "HTTP request failed" The requestUri is http://localhost:xxx/Roots, which works when I manually browse to it, but the StatusCode is 0, statusText is the empty string, and so on and so forth. I've looked at Fiddler, at it gets exactly what I expected.
I'm assuming there's some manner of flag that needs to be set, but none of the tutorials I've found have been of any help. It's assumed that it works out of the box, and I too had high expectations getting simple read access would be easy.
UPDATE:
it turns out Internet Explorer has been receiving the appropriate data as JSON, though it still doesn't populate the roots as it should. In FireFox it returns a "501 not implemented" error, because my GET request is being altered to be OPTION. I don't have a web.config file as would a project I started as a WCF service. This is just a console app in Visual Studio 2010. So I guess my question becomes "how do I better specify cross-domain behavior through JayData?"
Try This:
var oProviderConfig = {
name: 'oData',
oDataServiceHost: 'http://localhost:xxx/Roots/'
,enableJSONP: false
};
Also you have to enable CORS support from your webservice. If you are using .NET
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Max-Age" value="3600" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion" />
<add name="Access-Control-Allow-Methods" value="PUT, POST, GET, DELETE, MERGE, OPTIONS" />
</customHeaders>
</httpProtocol>

MVC how to validate DateTime field with also client validation

In my View Model I have setup a field with this attributes.
All work fine if the user enter the date and time in the correct format.
An error appear if the User do not insert the DateTime in the right format.
I would like have validation also in the client.
Could you tell me how to do it?
[Required]
[Display(Name = "Start DateTime")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy HH:mm}")]
public System.DateTime DateTimeStart { get; set; }
Getting format exceptions from a property of type DateTime is very annoying issue. It is a fairly common issue when working with validation on DateTime.
DataAnnotaions works on server side and to take their full advantage you need to add ModelState.IsValid() in your controller.
public ActionResult Index(MyViewModel model)
{
if(ModelState.IsValid())
{
// valid data received...
}
else
{
// Invalid data, add model error here and return view...
}
}
If you to make these work on client side then you need to include two additional JavaScript files in your code i.e. jquery.validate.js and jquery.validate.unobtrusive.js along with jQuery core library. By Default all of these files comes in basic MVC project and included in Layout.
It is important to note the order of including these files. jQuery core should always be at the top followed by validation libraries.
jquery.js
jquery.validate.js
jquery.validate.unobtrusive.js
Make sure the validation flags are turned on in web.config file of
MVC project. Go to this file and locate the following and set them
true if they are false.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
This should setup your validations to work on client side. You can decorate the model property with the RegularExpression.
[Required]
[RegularExpression("^(([0-2]?[0-9]|3[0-1])/([0]?[1-9]|1[0-2])/[1-2]\d{3}) (20|21|22|23|[0-1]?\d{1}):([0-5]?\d{1})$", ErrorMessage = "Invalid date")]
public string DateTimeStart { get; set; }
This will validate the datetime in dd-mm-yyyy hh:mm format.
Besides in this case you can make your property a string type also because regular expression will take care of your date format.
Apart from this, you can also create your custom DataAnnotation.
Firstly, what are you using to allow user to enter a date ?
If you are using Jquery DatePicker, then see this example there is no way the user can enter date in wrong format (except for inspecting the element and changing the textbox value, which can be ignored.)
Sample Code using Jquery Datepicker :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
</body>
</html>
and incase you are not using DatePicker I very strongly recommend you to use it.
Incase you are new to datepicker, you can go through the following listed articles to get started :
Introduction to jquery Date Picker in ASP.NET MVC
jQuery UI. Widgets. Datepicker (Calendar)

mvc foolproof validation client side script not showing until after form submitted

I am using foolproof on a couple question in an MVC 3 for. Specifically I have radio buttons with a textarea, if the radio button 'Yes' is selected, then the textarea can not be empty. I have other validation on some fields, using regular 'Required' attribute and those work fine, but the 'RequiredIfTrue' attributes do not validate on the client side. So if I fill in all the fields so they will validate, then click Yes on a radio but leave the corresponding textarea empty, then submit, the form hits the server instead of validating client side. I also noticed when Viewing the Source in the browser, the 'RequiredIfTrue' attributes are not added to the HTML until after the form is submitted.
I am using a ViewModel for this project, and that seems to be the problem. CUrrently the attributes are on the properties, which are in a model, then I refer to that model in the ViewModel and pass the ViewModel to the View. But if I put the properties directly in the ViewModel, it works correctly. I don't want the properties in hte ViewModel , because wouldn't I then need to add some kind of mapping code to the ViewModel so the properties are associated with the correct model/table?
These are the scripts included in the project:
<link href="#Url.Content("~/Content/mvc.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jquery-ui-1.8.22.custom.css")" rel="Stylesheet"" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.22.custom.min.js")" type="text/javascript""></script>
<script src="#Url.Content("~/Scripts/HistoryArrayTables.js")" type="text/javascript""></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/mvcfoolproof.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MvcFoolproofJQueryValidation.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MvcFoolproofValidation.min.js")" type="text/javascript"></script>
Here is part of the model:
using Foolproof;
namespace EligibityForm.Models
{
[MetadataType (typeof(HistoryMetadata))]
public partial class History
{
}
public class HistoryMetadata
{
[StringLength(2000)]
[RequiredIfTrue("HasComment", ErrorMessage="Please enter an explanation")]
[Display(Name = "Have you EVER been subject to a lawsuit?")]
public string Comment { get; set; }
public bool HasComment { get; set; }
}
And here is part of the ViewModel:
using Foolproof;
namespace EligibityForm.Models.CompositeModels
{
public class HistoryViewModel
{
public History HistoryModel { get; set; }
Thanks.

Asp.net MVC client validation, no client validation with sub-items?

I'm using asp.net mvc 3 for a project and already using the server and client validation on several pages. It works fine. But this time, I've a special case:
Items in the view are bounds to the model and also to some of its properties.
one example:
public class MyModelView{
[Required]
[StringLength(100, MinimumLength = 2)]
public String Name{get;set;}
public DetailsObject Details{get;set;}
}
public class DetailsObject{
[Required]
[StringLength(100, MinimumLength = 2)]
public String PropertyOne{get;set;}
[Required]
[StringLength(100, MinimumLength = 2)]
public String PropertyTwo{get;set;}
}
and in the view I've "bindings on all elements
#Html.TextBoxFor(m=>m.Name)
#Html.TextBoxFor(m=>m.Details.PropertyOne)
#Html.TextBoxFor(m=>m.Details.PropertyTwo)
The problem is that I don't get any client validations. The server validation is still working fine for all properties.
I've the jquery validate unobtrusive included. How do you manage that?
there are several places you should check
web.config should have those lines
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
check the javascripts to be included in right order
<script src="/Scripts/jquery-latest.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
also as a reminder (as I don't see the whole view file) place ValidationMessageFor helpers to see validation errors

Resources