c# how change datetime formart in a texbox (dd/MM/yyyy) in microsoft edge - model-view-controller

We have a problem with the datatime format in MS Edge. Our website is running properly in IE with the correct format (dd/MM/yyyy) in IE but if we use MS Edge the validation throws an error (is nto a valid date)
We want to maintain the textboxes, we do not want any datapicker
We have try 2 approaches:
Approach 1:
#Html.TextBoxFor(m => m.ConfigBPAValue.PurchaseDate, "{0:dd/MM/yyyy}", new { #class = "form-control default-date-picker" })
Approach 2:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime Quarter0Date { get; set; }
#Html.TextBoxFor(m => m.ConfigBPAValue.Quarter0Date, new { #class = "form-control" })
In both cases the application expects a (yyyy/MM/dd) format.
Have we missed anything?
thanks

I have changed the references
#Scripts.Render("~/Scripts/jquery-1.12.4.min.js")
#Scripts.Render("~/Scripts/jquery.validate.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
By
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
and now is working properly

Related

MVC4 client validation not displaying

When I submit my form, The client validation is working, but it is not displaying the error messages for the invalid form fields...
The Model
public class Blog : MainDbContext
{
public int Id { get; set; }
[Display(Name="Author")]
public int Profile { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Title is required.")]
public string Title { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "At least one Tag is required.")]
public string Tags { get; set; }
}
The ViewModel
public class BlogEditViewModel
{
public BlogEditViewModel(Blog blogItem, IEnumerable<SelectListItem> staffList)
{
this.BlogItem = blogItem;
this.StaffList = staffList;
}
public Blog BlogItem { get; set; }
public IEnumerable<SelectListItem> StaffList { get; private set; }
}
The View
<section>
#Html.LabelFor(model => model.BlogItem.Tags)
#Html.EditorFor(model => Model.BlogItem.Tags, null, "Tags")
#Html.ValidationMessageFor(model => model.BlogItem.Tags)
</Section>
The Layout
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
The Output (on form submitted)
<input type="text" value="ok" name="Tags" id="Tags" data-val-required="At least one Tag is required." data-val="true" class="text-box single-line input-validation-error">
<span data-valmsg-replace="true" data-valmsg-for="BlogItem.Tags" class="field-validation-valid"></span>
What i expect is the above Span tag to contain the error message as defined n the Model.
The problem I suspect relates to the naming in the EditorFor, as you can see I use an overload to specify the 'htmlfieldname', as without this the form data fails to map the form fields with the model & fails to save the submitted from data.
If I dont use the overloaded EditorFor, the validation works, but as mentioned above the, the form data fails to map the form fields with the model
how do I get the validation to work?
Thanks
kb
Add this script in your View and client side validation is working fine,
<script src="#Url.Content("~/Script/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Script/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
I think issue is you have to remove null, "Tags"
#Html.EditorFor(model => Model.BlogItem.Tags)
or you have to assign null, "Tags" to
#Html.ValidationMessage("Tags")
Ex:
View
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { Name="asd"})
#Html.ValidationMessage("asd")
Model
public class RegisterModel
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}

KendoUI grid filter not working

I am just starting with Kendo UI. I have a .NET MVC Razor project that will include a Kendo Grid. My page loads fine and looks good-the data is in the grid, but I have two issues:
when I click the "filter" icon, nothing happens (no pop-up, nothing)
when I run the page I get an error in visual studio inside the kendo.all.min.js file (Error: Microsoft JScript runtime error: Object doesn't suport this action. Code highlighted reads "d.transport=new n.data.transports[a.type](c(h,{data:i}))" Running in firebug gives this error: "n.data.transports[a.type] is not a constructor"
I am using a Model that is of type List(CustomViewModel). I have added the following scripts and css to my _Layout partial view:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.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.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/kendo.all.min.js")" type="text/javascript"></script>
(I tried using "kendo.web.min" and "kendo.aspnetmvc.min" in the place of "kendo.all.min" and I get the same result, but the error is in kendo.web.min.js)
My page looks like this:
#model List<CustomViewModel>
...
#(Html.Kendo().Grid(Model)
.Name("applicantGrid")
.Columns(columns =>
{
columns.Bound(p => p.ApplicationID);
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
})
.Sortable()
.Filterable()
.Pageable()
)
My View Model looks like this:
public class CustomViewModel
{
[ScaffoldColumn(false)]
public Guid CustomViewModelID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
}
I've noticed that in the Kendo examples (http://demos.kendoui.com/web/grid/local-data.html) the cursor is a hand when it's over the filter icon. On my page, the cursor is an arrow when it's over the filter icon.
Sorting works fine. I've also adjust this example a bit to get select and edit buttons working fine, but the filter just won't work.
I tried posting on the Kendo forums, but haven't gotten a response.
Try this:
Add to your ASP.NET MVC layout page:
<script src="#Url.Content("~/Scripts/kendo.web.min.js")"></script>
<script src="#Url.Content("~/Scripts/kendo.aspnetmvc.min.js")"></script>
For more information see this: http://www.kendoui.com/documentation/asp-net-mvc/introduction.aspx
And download the last scripts version. Apparently earlier versions of kendo.web.mindont have .Filterable() option.

Rectify the input at client side using RemoteValidation

Is there any possibility of rectifying the input at client side using Remote Validation?
For example, the user will enter the date as 010101 which means 01-Jan-2001, can Remote Validation reflect/pass the rectified value (010101 into 01-Jan-2001) at/to client side?
I have a scenario where i have JS to format the input into correct date format. Later on i had to use RemoteValidation. My remote validation receives date in ddmmyy format (RemoteValidation gets called before JS), it first converts it into correct date and then perform validation, and then my JS does not get called at all and so 010101 is not get converted into 01-Jan-2001.
Edit
There are two things i would like to get help for
1- Is there anyway a remote validation function can modify the model/data passed to it for validation and then pass it back to the view so that user can see the modified version of the model/data
[Deleted:2- I have JavaScript for a date field which formats the date when focus is lost. It is working fine. When i used Remote validation along with JS, the script does not get called at all.]
Edit
Model
public class master
{
public string sometext { get; set; }
public child mychild { get; set; }
}
public class child
{
public child()
{
thedate = DateTime.MaxValue;
}
[Remote("ValidateDate", "Test", ErrorMessage = "Invalid Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:mm/dd/yyyy}", NullDisplayText = "Enter Date")]
public DateTime? thedate { get; set; }
}
View
#model Models.master
#using Web.Framework
#{
Layout = null;
}
<html>
<head>
<title>Test - My ASP.NET MVC Application</title>
<script src="#Url.Scripts("jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Scripts("jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="#Url.Scripts("modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
<script src="#Url.Scripts("AjaxLogin.js")" type="text/javascript"></script>
<script src="#Url.Scripts("jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Scripts("jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Scripts("jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Scripts("MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Scripts("MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Scripts("myScripts.js")" type="text/javascript"></script>
</head>
<body>
#using (Html.BeginForm("testSubmit", "Test"))
{
#Html.LabelFor(m => m.sometext)
<br />
#Html.TextBoxFor(m => m.sometext)
<br />
#Html.LabelFor(m => m.mychild.thedate)
<br />
#Html.TextBoxFor(m => m.mychild.thedate, new { onblur = "doDate(this, '');" })
#Html.ValidationMessageFor(m => m.mychild.thedate)
<br />
<input type="submit" value = "Submit me" />
}
</body></html>
Controller
public ActionResult testSubmit(master model)
{
#ViewBag.Message = "OK";
return View("response");
}
public JsonResult ValidateDate(DateTime? thedate)
{
return Json(HttpContext.Request.QueryString["mychild.thedate"].ToString(), JsonRequestBehavior.AllowGet);
}
My remote validator always receives null in thedate, but i can access the value from query string but the value is unformatted i.e. Remote validation gets called before JS which means i have to format the date first in remote function and then validate, once validated then this input is formatted again by JS and both have to be synced.
Now, how can i get the formatted value in Remote function OR pass the formatted value from Remote function to the View ?
Since i didn't get any answer so the answer, so far, is "No".

MVC3 Remote Validation not Fired?

I created a very simple test project to illustrate the problem.
My model class
public class HomeModel
{
[Required(ErrorMessage="Missing property1.")]
public string Property1
{
get;
set;
}
[Remote("ValidateProperty2", "Home", HttpMethod="Get", AdditionalFields = "Property3", ErrorMessage="Property2 wrong!")]
public string Property2
{
get;
set;
}
public string Property3
{
get;
set;
}
}
My controller
public class HomeController : Controller
{
public ActionResult Index()
{
HomeModel model = new HomeModel();
return View(model);
}
[HttpPost]
public ActionResult Index(HomeModel model)
{
return View(model);
}
public ActionResult ValidateProperty2(string property2, string property3)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
And my view
#model RemoteValidationTest.Models.HomeModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.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>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
<body>
#using (Ajax.BeginForm(new AjaxOptions
{
HttpMethod = "POST"
}))
{
#Html.TextBoxFor(x => x.Property1) #Html.ValidationMessageFor(x => x.Property1)<br />
#Html.TextBoxFor(x => x.Property2) #Html.ValidationMessageFor(x => x.Property2)<br />
#Html.TextBoxFor(x => x.Property3) #Html.ValidationMessageFor(x => x.Property3)<br />
<input type="submit" />
}
</body>
</html>
And my web.config
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Nothing really fancy here. I havea model class with 3 properties. The first one is set be required and second one is remote validation, I believed I have create the action method properly. I set break piont to ValidateProperty2 function, it never gets called.
I also used FireBug, the same thing client side does not even try to call the server side.
What is wrong with the code here?
Edit 1:
I think I get something, the remote validation will only fires when the control (e.g text box) has value in side. The empty control will never trigger the validation. In my case I actually try to implmenet a more complicated logic, I need the validation to fire even when the control text is empty (to check other property's value). Is it even possible?
I have a working version here for mvc3:
http://completedevelopment.blogspot.com/2011/08/remote-ajax-validation-in-mvc3.html
d/l it and you can compare files.
The problem is that the validation don't fire automatically when you press the send button for the first time. Here is how you initiate the validation upon page load so that it fires every time it is needed on submit:
"Required" validation attribute not working in asp.net mvc 3 while others work

Client-side validation not firing for CompareAttribute DataAnnotation

I'm laying out a view that compares two password strings. The two properties in one of my models are pretty straightforward:
[Required]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed")]
[StringLength(20, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed")]
[StringLength(20, MinimumLength = 6)]
[Display(Name = "Confirm Password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
Here's my view code:
<table class="fieldset center" width="400">
<tbody>
<tr>
<th width="150">
#Html.LabelFor(m => m.NewPassword)
</th>
<td>
#Html.PasswordFor(m => m.NewPassword, new { #class = "itext3" })
<br /><br />#Html.ValidationMessageFor(m => m.NewPassword)
</td>
</tr>
<tr>
<th width="150">
#Html.LabelFor(m => m.ConfirmPassword)
</th>
<td>
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "itext3" })
<br /><br />#Html.ValidationMessageFor(m => m.ConfirmPassword)
</td>
</tr>
</tbody>
</table>
All of the attributes fire their client-side validation messages when tested, except for the CompareAttribute on ConfirmPassword which is not firing until I hit the server. However, in my controller the ModelState.IsValid = false.
I compared what I'm doing to the default MVC application which is working correctly. Any suggestions for troubleshooting and fixing this?
I'm using MVC 3 RTM.
There is a BUG in jquery.validate.unobtrusive.js (and jquery.validate.unobtrusive.min.js, the minified version). The client-side validation emitted as a result of the [Compare] attribute will ONLY work if the compare-to field is the FIRST field on the form. To fix this bug, locate this line in jquery.validate.unobtrusive.js:
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
which results in this equivalent:
element = $(options.form).find(":input[name=MyExample.Control]")[0];
Unfortunately that's not the right syntax for find(), and causes it to reference the first input control on the form.
Change that line to:
element = $(options.form).find(":input[name='" + fullOtherName + "']")[0];
which results in this equivalent:
element = $(options.form).find(":input[name='MyExample.Control]'")[0];
Which is the correct syntax, and correctly matches the input control with the specified name.
Locate the same code block in jquery.validate.unobtrusive.min.js, which looks like this:
f=a(b.form).find(":input[name="+d+"]")[0];
and change it to:
f=a(b.form).find(":input[name='"+d+"']")[0];
Take a look at your script tags in your _Layout.cshtml. I'm guessing the issue is probably your jQuery references. Did you start the MVC 3 project form scratch or are you using an example project or something like that?
Here is what happend with me; I had similar issues...
I was using some example code that pointed to ajax.microsoft.com in the src attributes
So, for example one of the script tags looked like this: <script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
I wanted to get a better handle on what js was executing on the client side so I changed it to this: <script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
That is just an example, I think there were a couple more script tags that I changed as well
So, after changing to internally served jQuery files it worked. I went back and looked at my local .validate.js file... and it was version 1.6. That is how i realized the issue was due to the version of jQuery or it's compatibility with one of the other the js libs anyway.
Bottom line is that it looks like 1.7 doesn't fully function with the validate.unobtrusive.js lib that I had... there may be a newer version that does function with 1.7... like I said, I was tinkering with an example project so there are some unknowns there. I suppose it could also be an incompatibility with the MvcValidation.js lib between it and one of the other js libs too?
At any rate, I'd say the simplest way to state your issue is that you are most likely referencing a bad combination of js libs. I'd say the best failsafe way to get a good combination of js libs is to create a new Asp.Net MVC 3 Project in Visual Studio and see what versions it gives you by default/with the project template... that is assuming that you didn't start the project from scratch. If you DID start it from scratch then may be you changed your layout file to have bad js references or if none of that is true then I suppose it could be a problem with the VisualStudio project templates?... realistically I'd say that is doubtful though. All of that said- I'd say the most likely cause [that I'd wager on anyway] is that you just got in trouble like me trying to quickly use some example code =)
I've tested this with ASP.NET MVC 3 RTM and it worked fine for me:
Model:
public class MyViewModel
{
[Required]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed")]
[StringLength(20, MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[Required]
[DataType(DataType.Password)]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed")]
[StringLength(20, MinimumLength = 6)]
[Display(Name = "Confirm Password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
#model SomeAppName.Models.MyViewModel
#{
ViewBag.Title = "Home Page";
}
<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>
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.NewPassword)
#Html.PasswordFor(m => m.NewPassword)
#Html.ValidationMessageFor(m => m.NewPassword)
<br/>
#Html.LabelFor(m => m.ConfirmPassword)
#Html.PasswordFor(m => m.ConfirmPassword)
#Html.ValidationMessageFor(m => m.ConfirmPassword)
<br/>
<input type="submit" value="OK" />
}
In this configuration client side validation works perfectly fine for all attributes including the [Compare].
I was never able to make the default way to work. Seems like in JQuery it fires only those validation methods that are registered with JQuery.validator.
Initially I was doing something like this...
jQuery.validator.unobtrusive.adapters.add("equaltopropertyvalidation", ["param"], function (rule)
{
alert("attaching custom validation adapter.");
rule.rules["equaltopropertyvalidation"] = rule.params.param;
rule.messages["equaltopropertyvalidation"] = rule.message;
return function (value, element, param)
{
alert("now validating!");
return value == this.currentForm[param].value;
};
});
But my second alert (now validating!) would never fire even though the first one would. I had seen this article but I was hesitating to implement it like this because it requires me to do something extra but I was lazy.
Well after spending lots of time to figure out what's wrong I implemented it in the way this article suggests and it works. Now it is like this and it works.
<script type="text/javascript">
jQuery.validator.addMethod("equaltopropertyvalidation", function (value, element, param)
{
return value == this.currentForm[param].value;
});
jQuery.validator.unobtrusive.adapters.add("equaltopropertyvalidation", ["param"], function (rule)
{
rule.rules["equaltopropertyvalidation"] = rule.params.param;
rule.messages["equaltopropertyvalidation"] = rule.message;
});
</script>
If you like detail then here it is: Look in jquery.validate.js and search for
check: function (element)
This is the function that is fired to check if the field is valid or not by firing all the applicable rules on the field. Now first it creates an array or rules to fire. It does that using the following code.
var rules = $(element).rules();
Then it iterates over the rules collection, creates a rule element for every item in the collection and then tries to find a corresponding method to fire for that rule. Once the method is found it is fired. It does that using the following code.
var result = $.validator.methods[method].call(this, element.value.replace(/\r/g, ""), element, rule.parameters);
Now the important thing is that if your custom method is not added to the $.validator.methods collection using the JQuery.validator.addMethod IT WILL NOT BE FOUND, even if it is sitting there in the JQuery.validator.unobtrusive.adapters collection.
There might be a way to make this work without using the JQuery.validator.addMethod (and if yes then someone please clarify) but this I believe is the reason the second approach works and the first doesn't.
I was using the following versions of Jquery files
JQuery: 1.6/1.7.1
Jquery.Validate: 1.9.0
JQuery.Unobtrusive.Validate: taken from Microsoft CDN on
2/14/2012.

Resources