新手在这里。但是在发布之前已经做了一些阅读和搜索。最近几天一直在摸不着头脑。
请注意,我正在尝试使用MVC(而不是Javascript)进行验证
我创建了自定义日期验证属性,并将该属性应用于模型中的相应字段。但是,我的观点并未反映自定义验证错误。但是,如果我应用默认属性,我的视图会反映基本验证错误(请参阅正则表达式)。
我试图实施使用, 1.自定义属性。 2.实现IValidateObject接口。
两者都不适用于日期对象。但是,调试代码时我注意到,当IsValid或Validate被命中时,将返回ValidationResult。
请注意,我使用过Ajax.BeginForm(不确定这是否会给我带来麻烦)。
模型
public class RatePlanFixedFeeSearchCriteriaViewModel : IValidatableObject
{
/// <summary>
/// Rate Plan ID
/// </summary>
public int RatePlanId { get; set; }
/// <summary>
/// Rate Plan Name
/// </summary>
[Display(ResourceType = typeof(UIResources.RatePlanFixedFee), Name = "RatePlan")]
public string RatePlan { get; set; }
/// <summary>
/// notes
/// </summary>
[Display(ResourceType = typeof(UIResources.GeneralPurpose ), Name = "Notes")]
public string Notes { get; set; }
/// <summary>
/// Start Date
/// </summary>
[DisplayFormat(DataFormatString = "{0:d}",ApplyFormatInEditMode=true)]
[Display(ResourceType = typeof(UIResources.GeneralPurpose), Name = "StartDate")]
//[RegularExpression(@"^[0-9]{0,15}$", ErrorMessage = "Yoo...not a number")]
[IsDateAfterAttribute("EndCreatedDate", true)]
public DateTime StartCreatedDate { get; set; }
/// <summary>
/// End Date
/// </summary>
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(ResourceType = typeof(UIResources.GeneralPurpose), Name = "EndDate")]
//[RegularExpression(@"^[0-9]{0,15}$", ErrorMessage = "Yoo...not a number")]
[IsDateAfterAttribute("StartCreatedDate", true)]
public DateTime EndCreatedDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (StartCreatedDate > EndCreatedDate)
yield return new ValidationResult("StartCreatedDate > EndCreatedDate", new[] { "StartCreatedDate", "EndCreatedDate" });
}
}
//[IsDateAfterAttribute("StartCreatedDate", true)]
//[StringLength(10, ErrorMessage = "EndCreatedDate Should be less than 10")]
public sealed class IsDateAfterAttribute : ValidationAttribute
{
private readonly string testedPropertyName;
private readonly bool allowEqualDates;
public IsDateAfterAttribute(string testedPropertyName, bool allowEqualDates = false)
{
this.testedPropertyName = testedPropertyName;
this.allowEqualDates = allowEqualDates;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
if (propertyTestedInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
}
var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
if (value == null || !(value is DateTime))
{
return ValidationResult.Success;
}
if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
{
return ValidationResult.Success;
}
// Compare values
if ((DateTime)value >= (DateTime)propertyTestedValue)
{
if (this.allowEqualDates && value == propertyTestedValue)
{
return ValidationResult.Success;
}
else if ((DateTime)value > (DateTime)propertyTestedValue)
{
return ValidationResult.Success;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { "EndCreatedDate" });
}
}
查看(我在这里发布整个视图。请耐心等待我)
@model MyModel
@using (...)
{
<div id="ErrMsg" class="validation-summary-errors center">
</div>
@Html.ValidationSummary()
@Html.ValidationMessageFor(model => model.StartCreatedDate)
@Html.ValidationMessageFor(model => model.EndCreatedDate)
using (Ajax.BeginForm("ratePlanFixedFeeResults", "RatePlanFixedFee", new AjaxOptions()))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
@Html.ValidationMessageFor(model => model.StartCreatedDate)
@Html.ValidationMessageFor(model => model.EndCreatedDate)
<fieldset class="control-set-container no-border">
<ul class="undecorated-list inline-list-items">
<li>
@Html.LabelFor(model => model.RatePlan, new { @class = "label-with-colon tabletextbold" })
@Html.DisplayFor(model => model.RatePlan, new { Id = "Rateplan" })
@Html.HiddenFor(model => model.RatePlanId)
</li>
<li>
@Html.LabelFor(model => model.Notes, new { @class = "label-with-colon tabletextbold" })
@Html.DisplayFor(model => model.Notes)
</li>
</ul>
</fieldset>
<fieldset class="control-set-container no-border">
<ul class="undecorated-list inline-list-items">
<li><button id="NewBtn" type="button" onclick="return fixedFee('@Model.RatePlanId');">@UIResources.GeneralPurpose.New</button>
<li>
<span>@UIResources.RatePlanFixedFee.CreatedWithin</span>
</li>
<li>
@Html.LabelFor(model => model.StartCreatedDate)
@Html.CCLGDateTimePicker(model => model.StartCreatedDate)
</li>
<li>
@Html.LabelFor(model => model.EndCreatedDate)
@Html.CCLGDateTimePicker(model => model.EndCreatedDate)
</li>
<li>
<button id="OkButton" type="submit">@UIResources.GeneralPurpose.OK </button>
</li>
</ul>
</fieldset>
}
<div id="RatePlanFixedFeeResults" class="validation-summary-errors">
</div>
<div id="ViewActionButtons" class="content-center">
<button id="CloseBtn" type="button">@UIResources.GeneralPurpose.Close</button>
</div>
}
@section ViewBodyScripts
{
<script type="text/javascript">
function fixedFee(RatePlanId) {
var grid = $("#Grid").data("kendoGrid");
var numOfRows = 0;
if (grid != undefined) {
numOfRows = grid.dataItems().length;
}
window.location.href = '@Url.Action("Create", "RatePlanFixedFee")?ratePlanId=' + RatePlanId + '&fixedFeeConfigurationId=' + RatePlanId + (parseInt(parseInt(numOfRows) + 1));
}
</script>
<script type="text/javascript">
$(document).ready(function () {
if (validateDate()) {
$('#ErrMsg').html('');
$.post('/CC/RatePlanFixedFee/ratePlanFixedFeeResults', $('form').serialize(), function (response) {
if (response.indexOf('table') == -1) {
$('#RatePlanFixedFeeResults').html('');
$('#ErrMsg').html(response);
}
else {
$('#ErrMsg').html('');
$('#RatePlanFixedFeeResults').html(response);
}
});
}
else {
$('#RatePlanFixedFeeResults').html('');
}
$('#CloseBtn').click(function () {
window.location.href = '/CC/RatePlan/List';
});
$('#OkButton').click(function () {
if (true) { //Modified
$('#ErrMsg').html('');
$.post('/CC/RatePlanFixedFee/ratePlanFixedFeeResults', $('form').serialize(), function (response) {
if (response.indexOf('table') == -1) {
$('#RatePlanFixedFeeResults').html('');
$('#ErrMsg').html(response);
}
else {
$('#ErrMsg').html('');
$('#RatePlanFixedFeeResults').html(response);
}
});
return true;
}
else {
$('#RatePlanFixedFeeResults').html('');
return false;
}
});
});
</script>
<script type="text/javascript">
function validateDate() {
var sdate = $("input[name='StartCreatedDate']").val();
var edate = $("input[name='EndCreatedDate']").val();
var date_format = /^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_format.test(sdate))) {
$('#ErrMsg').html('@UIResources.GeneralPurpose.EnterValidStartDateText');
return false;
}
if (!(date_format.test(edate))) {
$('#ErrMsg').html('@UIResources.GeneralPurpose.EnterValidEndDateText');
return false;
}
var startDate = convertToDateFormat(new Date(sdate));
var endDate = convertToDateFormat(new Date(edate));
var todaydate = convertToDateFormat(new Date());
if (sdate != '' && edate != '' && startDate > endDate) {
$('#ErrMsg').html('@UIResources.GeneralPurpose.StartDateMustPrecedeEndDateText');
return false;
}
else if (startDate > todaydate) {
$('#ErrMsg').html('@UIResources.GeneralPurpose.StartDateErrorMsg');
return false;
}
else if (endDate > todaydate) {
$('#ErrMsg').html('@UIResources.GeneralPurpose.EndDateErrorMsg');
return false;
}
return true;
}
function convertToDateFormat(date) {
var dateString = ("0" + (date.getMonth() + 1).toString()).substr(-2) + "/" + ("0" + date.getDate().toString()).substr(-2) + "/" + (date.getFullYear().toString());
return new Date(dateString);
}
</script>
<script type="text/javascript" src="@Url.Content("~/Scripts/globalize.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/globalize.cultures.js")"></script>
<script type="text/javascript" src="@Url.Content("~/ViewScripts/LGDateTimePicker.js")" data-cc-dashboard="ExecutiveDashboard"></script>
}
控制器操作方法
[AcceptVerbs(HttpVerbs.Post)]
public async Task<ActionResult> RatePlanFixedFeeResults(RatePlanFixedFeeSearchCriteriaViewModel searchCriteriaViewModel)
{
ViewBag.PageSize = orgSettings.MaxNoOfRows;
try
{
var ratePlanFixedFeeSearchCriteriaModel = Mapper.Map<RatePlanFixedFeeSearchCriteriaModel>(searchCriteriaViewModel);
var ratePlanFixedFeeSearchResultViewModelList = await GetRatePlanFixedFees(ratePlanFixedFeeSearchCriteriaModel);
if (ratePlanFixedFeeSearchResultViewModelList != null && ratePlanFixedFeeSearchResultViewModelList.Count > 0)
{
ratePlanFixedFeeSearchResultViewModelList.Each(x => x.EffectiveDate = orgSettings.DefaultTimeZone.ToLocalTime(x.EffectiveDate));
TempData["EffectiveDateList"] = ratePlanFixedFeeSearchResultViewModelList.Select(x => x.EffectiveDate.Date).ToList();
return PartialView("_Results", ratePlanFixedFeeSearchResultViewModelList);
}
else
{
if (TempData.ContainsKey("EffectiveDateList"))
{
TempData.Remove("EffectiveDateList");
}
return Content(UIResources.GeneralPurpose.SearchReturnedNoRecords);
}
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "RatePlanFixedFeeController", "RatePlanFixedFeeResults"));
}
}