One individual jQuery UI DatePicker not working - asp.net-mvc

I have three text inputs on a view. All have the class datepicker.
#Html.TextBox("Dummy", DateTime.Now, new { #class = "datepicker" })
#Html.EditorFor(model => model.StartDate)
#Html.EditorFor(model => model.EndDate)
The bottom two are covered by my DateTime editor template:
#model DateTime?
#{
string editText = Model.HasValue ? Model.Value.ToShortDateString() : "";
}
#Html.TextBox("", editText, new { #class = "datepicker" })
These are set up for date pickers in my _Layout template in the following code:
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy/mm/dd"
});
});
Now the date picker popup for StartDate, only, is totally unresponsive. It won't even change months, never mind pick a date. All three inputs are the same. Both StartDate and EndDate are non-nullable DateTime fields declared as:
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
public DateTime EndDate { get; set; }
I am using jQuery 1.10.2 and jQuery UI 1.10.3, both installed via NuGet. I had to include the following script to get the DatePickers working:
<script src="http://code.jquery.com/jquery-migrate-1.1.1.js"></script>
I am totally stymied.
AMENDMENT:
Errors show in the Javascript console:
Clicking on a day produces the error "Cannot set property 'currentDay' of undefined".
Clicking on the previous or next month icon produces "Cannot read property 'settings' of undefined"

I guess you don't have an unique id for the textbox?
an unique id is required for the datepicker.
either add it in the javascript
$(function () {
$(".datepicker:not(.hasdatepicker)").uniqueId().datepicker({
dateFormat: "yy/mm/dd"
});
});
or add it in razor
#Html.TextBox("", editText, new { #class = "datepicker", id = string.Format("datepicker-{0:N}", Guid.NewGuid()) })

I've used exact version of each script file (jQuery,jQuery UI, jQuery migrate) and used your code and found no error. It works fine without any issue.
Modal:
public class Test
{
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
public DateTime EndDate { get; set; }
}
Edit View:
#model MvcApplication2.Models.Test
#{
ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Test</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Test</legend>
<div class="editor-label">
#Html.LabelFor(model => model.StartDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EndDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EndDate)
#Html.ValidationMessageFor(model => model.EndDate)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Shared/EditorTemplates/DateTime.Cshtml
#model DateTime?
#{
string editText = Model.HasValue ? Model.Value.ToShortDateString() : "";
}
#Html.TextBox("", editText, new { #class = "datepicker" })
<script type="text/javascript">
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy/mm/dd"
});
});
</script>
Below is the order of CSS and JS files.
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/jquery-ui.css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/Scripts/jquery-migrate-1.1.1.js")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/modernizr")
It seems something else is causing the issue and not any script file or anything else. You might want to try my code in new project.

Use this link for more info: http://jqueryui.com/datepicker/
And try to change mm to MM
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy/MM/dd"
});
});
Second answer:
Try using this date/time picker:
http://tarruda.github.io/bootstrap-datetimepicker/
or
http://www.eyecon.ro/bootstrap-datepicker/
I used them both, and worked for me.
Hope this helpes.

Related

Date DataAnnotation validation attribute not working - shows the time

Not working. Date comes back from a database field. Shows as:
When it is not set from a database as there is no birth date, I get a little red dot top left. Shows as:
I don't want the time included. I have a data annotation display format but it does not seem to take affect.
My Model(not showing other fields) is:
using System;
using System.ComponentModel.DataAnnotations;
namespace GbngWebClient.Models
{
public class UserProfileForMaintViewModel
{
// Can be null.
[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[RegularExpression(#"(((0[1-9]|1[0-2])\/(0|1)[0-9]|2[0-9]|3[0-1])\/((19|20)\d\d))$", ErrorMessage = "Invalid date format.")]
public DateTime BirthDate { get; set; }
}
}
My view (not showing other fields) is:
#model GbngWebClient.Models.UserProfileForMaintViewModel
<h1 class="page-header">User Profile Maintenance</h1>
#{
ViewBag.Title = "UserProfileMaint";
Layout = "~/Views/Shared/_LayoutUser.cshtml";
}
#using (Html.BeginForm("UpdateUserProfile", "UserProfiler", FormMethod.Post))
{
<div style="margin-top:10px;"></div>
<div class="panel panel-default">
<div class="panel-heading">Your Profile</div>
<div class="panel-body">
<div class="row">
<div class="row">
<div class="col-md-3">
#Html.LabelFor(model => model.BirthDate, new { #class = "manadatory" })
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
</div>
<div class="col-md-3"></div>
</div>
<div style="margin-top:10px;"></div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-0 col-md-12">
#* Submit button. *#
<input type="submit" value="Save" class="btn btn-info" />
</div>
</div>
</div>
</div>
</div>
}
From my previous experience I found out that it is much easier to deal with a string than a DateTime variable. So I usually use it as a hack. You can have an extra text field in your ViewModel and format it from the controller for the view -
public ActionResult Custom2()
{
var profile = new Profile();
profile.DoB = DateTime.Now.Date;
profile.DoBText = profile.DoB.ToString("yyyy-MM-dd");
return View(profile);
}
Now the view can accept the text data without any problem
#model mvcDeploymentTest.Models.Profile
#{
ViewBag.Title = "Custom2";
}
<h2>Custom2</h2>
#using (Html.BeginForm("PostTest", "Home", FormMethod.Post))
{
#Html.TextBoxFor(model => model.DoBText, new { #class = "form-control", Type = "date" })
<input type="submit" value="Submit" />
}
And once posted, you can parse the changed text value to datetime again with any formatting you want
[HttpPost]
public void PostTest(Profile myProfile)
{
DateTime dateValue;
if (!string.IsNullOrEmpty(myProfile.DoBText))
{
DateTime.TryParseExact(myProfile.DoBText,"yyyy-MM-dd", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateValue);
myProfile.DoB = dateValue;
}
return;
}
ApplyFormatInEditMode is only used/applied when using EditorFor - you have to use the overload for TextBoxFor which accepts a format string in order to get a formatted output in the rendered <input />.
#Html.TextBoxFor(model => model.BirthDate, "{0:d}", new { #class = "form-control" })
{0:d} will apply whatever short date format matches your app's culture settings. Replace that with a custom format string if you want something else.
If you want to use your browser's native date input (<input type="date" />), you'll need to use an ISO-8601 short date, which is YYYY-MM-DD. An example:
#Html.TextBoxFor(model => model.BirthDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date" })
The default modelbinder knows how to transform that into a DateTime object, which you can then format into whatever else you wanted/needed.

Client-Side unobtrusive validation not working as expected

I am implementing Custom Unobtrusive client-side JavaScript for an MVC Application. The custom validation method ([EnforceTrue] Attribute) does fire when I press the submit button, but it does not have any effect. In the submit event, The Form.valid() method returns true, in spite of the custom method returning a false value. (I hardcoded it to false).
I have read up on Stackoverflow on the topic of Unobtrusive validation and found a myriad of designs , options, ideas, suggestions etc that did not exactly help. I tried referencing code libraries through nuget packages. I moved my code to the top of my View instead of having it at the bottom. I tried this with more complex validation logic but it still behaves the same. Eventually I scaled down my app to a few lines of code, to reproduce the behaviour.
This is my model: It contains a required Name field and a checkbox that needs to be checked, before submission. The checkbox requires the custom validation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection; // AtLeastOneProperty
using System.Web.Mvc; // Client side Validation STuff (26/08/19)
namespace WebApplication7_POC.Models
{
public class Consultant
{
[Required, Display(Name = "First name:"), MaxLength(80)]
public string FIRSTNAME { get; set; } // FIRSTNAME
[Display(Name = "I give my concent.")]
[EnforceTrue] // TEST 123
public bool Concent { get; set; } // AccessAdditional
}
public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
return (bool)value == true;
}
public override string FormatErrorMessage(string name)
{
return "The '" + name + "' field must be checked in order to continue.";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
ValidationType = "enforcetrue"
};
}
}
}
Below is the View. It implements the JQuery for the Custom validation at the top. On the botom, it catches the submit event and then checks if the form has validated. valid().
#model WebApplication7_POC.Models.Consultant
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<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>
<script type="text/javascript">
(function ($) {
// TEST 123
$.validator.addMethod("enforcetrue", function (value, element, param) {
alert('client validation trigerred!');
console.log(element);
console.log(element.checked);
return false; // element.checked;
});
$.validator.unobtrusive.adapters.addBool("enforcetrue");
}(jQuery));
</script>
#{
ViewBag.Title = "Consultant";
}
<h2>Consultant</h2>
#using (Html.BeginForm("Consultant","Home",FormMethod.Post,new { id = "HelloForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Consultant</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FIRSTNAME, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FIRSTNAME, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FIRSTNAME, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Concent, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Concent)
#Html.ValidationMessageFor(model => model.Concent, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit it!" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
$(document).ready(function () {
$("#HelloForm").submit(function () {
alert('HelloForm submit trigerred');
// https://stackoverflow.com/questions/53934575/asp-net-core-unobtrusive-client-side-validation-form-onsubmit-fires-even-on-vali
if ($("#HelloForm").valid()) {
// Show the Spinner
alert('Valid!');
// Sure this works, but it does not validate the custon validation rules.
// $("#LoaderSpinner").show('hidden');
// $(".overlay").show();
} else {
alert('Not Valid');
}
});
});
</script>
There is a controller that handles the Postback, but my issue is doing the client side validation.
When the submit button is pressed I expect the valid() method to return false when the checkbox is unchecked and show the error message on the screen (like the default [Required] attribute is doing).
Maybe there is just an oversight on my side somewhere?
Removing the
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
snippet, that included jquery a second time, resolved the issue eventually.

JQuery Datetimepicker date selected does not match date today

I am working on a scheduling project in MVC 5. I want to check the Date Selected against current Date. If they match, display the scheduled appointment for Today' date only in a view. Currently, the appointments do not display when I add "appointment.AppointmentDate == DateTime.Now". Instead the View duplicates "No Appointments Today'.
I have researched through StackOverFlow and other sites to try and figure out with no luck. One attempt was adding ".data('date') in the Create view: " $('#datetimepicker1.data('date'), #datetimepicker2').datetimepicker " to set the type as Date but was unsuccessful. I am a beginner and hope someone may be able to help me in the right direction. Thanks.
My code is below:
MODEL:
public enum AppointmentTime
{
_1pm_to_2pm, ApplicationDbContext _dbContext = new ApplicationDbContext();
public ActionResult Create(int id)
{
Property property = _dbContext.Properties.SingleOrDefault(b => b.PropertyID == id);
ViewBag.propertyName = property.PropertyName;
Consultation consultation = new Consultation();
consultation.PropertyID = id;
return View(consultation);
}
[HttpPost]
public ActionResult Create(Consultation consultation)
{
try
{
if (ModelState.IsValid)
{
Property property = _dbContext.Properties.SingleOrDefault(b => b.PropertyID == consultation.PropertyID);
property.Consultations.Add(consultation);
_dbContext.SaveChanges();
return RedirectToAction("Details", "Property", new { id = property.PropertyID });
}
return View();
}
catch
{
return View("Error");
}
}
_2pm_to_3pm,
_3pm_to_4pm,
_4pm_to_5pm,
_5pm_to_6pm
}
public class Consultation
{
[Key]
public int AppointmentID { get; set; }
[ForeignKey("Property")]
public int PropertyID { get; set; }
[Display(Name = "Enter your name")]
public string AppointmentName { get; set; }
[Required]
[Display(Name = "Email")]
public string AppointmentEmail { get; set; }
[Display(Name = "Select Date")]
[UIHint("AppointmentDate")]
[Required]
public DateTime AppointmentDate { get; set; }
public AppointmentTime AppointmentTime { get; set; }
public virtual Property Property { get; set; }
}
CONTROLLOR:
[Authorize(Roles = "Admin")]
public ActionResult AdminAppointmentView(Consultation consultaion)
{
var appointments = _dbContext.Consultations.ToList();
return View(appointments);
}
CREATE VIEW
#model OpenProperties.Models.Consultation
#{
ViewBag.Title = "Create Appointment";
}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css"
rel="stylesheet">
<link rel="stylesheet" type="text/css" media="screen"
href="http://tarruda.github.com/bootstrap-datetimepicker/assets/css/bootstrap-datetimepicker.min.css">
#using (Html.BeginForm(new { enctype = "multipart/form-data", id = "form1" }))
{
#Html.ValidationSummary(true)
<div>
#Html.HiddenFor(model => model.PropertyID)
<br />
<div class="form-group">
#Html.LabelFor(m => m.AppointmentName)
#Html.TextBoxFor(m => m.AppointmentName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AppointmentEmail)
#Html.TextBoxFor(m => m.AppointmentEmail, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.AppointmentTime, new { #class = "control-label col-md-2" })
#Html.EnumDropDownListFor(model => model.AppointmentTime)
#Html.ValidationMessageFor(model => model.AppointmentTime)
</div>
<div id="datetimepicker1" class="input-append date">
#Html.TextBoxFor(m => m.AppointmentDate, "{0:dd/MM/yyyy HH}",
new { placeholder = "App Date", #class = "dtPicket" })
<span class="add-on">
<i data-time-icon="icon-time"
data-date-icon="icon-calendar"></i>
</span>
</div>
<br />
<br />
<input type="submit" value="Submit" />
</div>
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.pt-BR.js">
</script>
<script type="text/javascript">
$('#datetimepicker1, #datetimepicker2').datetimepicker({
format: 'dd/MM/yyyy'
});
</script>
}
AdminAppointmentView VIEW:
#model IEnumerable<OpenProperties.Models.Consultation>
<h2>Todays Appointments</h2>
#foreach (var appointment in Model)
{
if (appointment.AppointmentDate == DateTime.Now)
{
<li>
<ul>#appointment.AppointmentID</ul>
<ul>#appointment.AppointmentDate</ul>
<ul>#appointment.AppointmentEmail</ul>
<ul>#appointment.AppointmentName</ul>
<ul>For Property ID: #appointment.PropertyID</ul>
</li>
}
else
{
<ul> No Appointments Today </ul>
}
}
Just at first Glance.
if (appointment.AppointmentDate == DateTime.Now)
(
}
Is the date Format is same for appointment.AppointmentDate and DateTime.Now??.
If not just add Tostring Method to these date.
ex.
DateTime.Now.ToString("MMMM dd, yyyy")
2) You might check the // Difference in days, hours, and minutes. between the date as well. Instead of comparing
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
3) You can format date in datetime Picker as follows.
$('#datepicker').datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm:ss"
});
4) Also could you please put Script and datepicker code before the html
<script type="text/javascript"
src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript"
src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.min.js">
</script>
<script type="text/javascript"
src="http://tarruda.github.com/bootstrap-datetimepicker/assets/js/bootstrap-datetimepicker.pt-BR.js">
</script>
<script type="text/javascript">
$('#datetimepicker1, #datetimepicker2').datetimepicker({
format: 'dd/MM/yyyy'
});
</script>

MVC ajax form submission returns default date of DateTime property

I am using the below Ajax form to select and post date ranges.
View Model:
public class ViewFormSubmissionsVM
{
public string FormName { get; set; }
public Guid FormId { get; set; }
[Display(Name="From:")]
public DateTime From { get; set; }
[Display(Name = "To:")]
public DateTime To { get; set; }
}
Razor/HTML:
#model ViewFormSubmissionsVM
#using (Ajax.BeginForm("ViewFormSubmissions", "Form", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onGetSubmissionSuccess", OnFailure = "onGetSubmissionError" }, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.FormId)
<div class="row col-md-12">
<div class="pull-right">
<label class="control-label col-md-3">#Html.DisplayNameFor(x => x.From)</label>
#Html.TextBoxFor(x => x.From, "{0:MM/dd/yyyy}", new { #class = "form-control col-md-3", #data_picker = "date-picker" })
<label class="col-md-3">#Html.DisplayNameFor(x => x.To)</label>
#Html.TextBoxFor(x => x.To, "{0:MM/dd/yyyy}", new { #class = "form-control col-md-3", #data_picker = "date-picker" })
<input type="submit" class="btn btn-primary" value="Search" />
</div>
</div>
}
JQuery Date picker:
$(document).ready(function () {
$('*[data-picker="date-picker"]').datepicker();
});
This issue is while submitting the form, the "From" and "To" Datetime properties, received the default date values instead of selected.
Am I missing anything important!! I have already used these codes in different forms, but never experienced this before.
Could any one help me to get out of this one.
Many Thanks.
First of all, I think you should call this overload:
using (Ajax.BeginForm("ViewFormSubmissions", "Form", null, new AjaxOptions{
HttpMethod = "POST",
OnSuccess = "onGetSubmissionSuccess",
OnFailure = "onGetSubmissionError"
},
new {#class = "form-horizontal" }))
with null as 3rd parameter.
Second, check your datetime format. You can find more info here: MVC DateTime binding with incorrect date format, ASP.NET MVC datetime culture issue when passing value back to controller or http://weblogs.asp.net/melvynharbour/mvc-modelbinder-and-localization.

Jquery validations stops working for an input when using masked plugin

Controller
public class HomeController : Controller
{
public ActionResult Index()
{
TestModel model = new TestModel();
return View(model);
}
}
Model
public class TestModel
{
[Required(ErrorMessage="You have to put a first name!")]
[StringLength(maximumLength: 24)]
[Display(Name="First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Yo the last name is required!")]
[StringLength(maximumLength: 24)]
public string LastName { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public string ZipCode {get; set;}
}
View
<h2>Test</h2>
#using(Html.BeginForm())
{
#Html.LabelFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
<br />
#Html.LabelFor(model => model.LastName)
#Html.TextBoxFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
<br />
#Html.LabelFor(model => model.PhoneNumber)
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
<br />
#Html.LabelFor(model => model.ZipCode)
#Html.TextBoxFor(model => model.ZipCode)
#Html.ValidationMessageFor(model => model.ZipCode)
<br />
<input type="submit"/>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
// Masked plugin script here, linking to site doesn't work
</script>
<script type="text/javascript">
$(document).ready(function () {
// Validation works when masks are commented out
$("#PhoneNumber").mask("(999) 999-9999");
$("#ZipCode").mask("99999");
});
</script>
.Net Fiddle
https://dotnetfiddle.net/qndNxE
Problem
If the two calls to the mask plugin are commented out validation works fine. This means that if I:
Enter something into the first name and last name text boxes and then
Tab out of each box and back in and hit delete to clear the
contents
Validation messages appear telling me that the fields are required.
If I uncomment out the two calls to the mask plugin and repeat the two steps above, one of the textboxes (first or last) will not display its validation message.
Can anyone tell me why this happens and what to do to get around it?
I wasn't able to find out the cause but what I ended up doing until we can get a better library situation to work around the problem is to handle the input event for the form inputs and mark them dirty and validate them if they are:
$("#myForm input").on("input", function () {
$("#myForm").data("validator").element(this);
});

Resources