[英]Date input validation asp.net
Working in visual studio and have the current code in my controller class called GroupController. 在Visual Studio中工作,并将当前代码包含在我的名为GroupController的控制器类中。 On the groups page, I can create a new group.
在网上论坛页面上,我可以创建一个新网上论坛。 The user will then enter String values for groupName, groupAssignment, groupLocation, and GroupDateTime.
然后,用户将为groupName,groupAssignment,groupLocation和GroupDateTime输入字符串值。 The code I have so far is provided below, but have struggled to find a working comparison for dates.
我到目前为止提供的代码在下面提供,但是一直在努力寻找有效的日期比较。 I want to make sure that Input date is greater than the current date.
我想确保输入日期大于当前日期。 If not, it will not allow the user to create a group.
如果不是,它将不允许用户创建组。 Any suggestions?
有什么建议么? Thank you
谢谢
public ActionResult Create([Bind(Include = "GroupID,GroupName,GroupAssignment,GroupLocation,GroupDateTime")] Group group)
{
var currentUser = manager.FindById(User.Identity.GetUserId());
try
{
group.User = manager.FindById(User.Identity.GetUserId());
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception /* dex */)
{
if(group.User == null)
{
ModelState.AddModelError("", "No user logged in");
}
else
{
ModelState.AddModelError("", "Unhandled Error");
}
}
return View(group);
}
Before your try
statement you could use DateTime.TryParse
. 在您的
try
语句之前,可以使用DateTime.TryParse
。 If that returns false, then add an error to ModelState
. 如果返回false,则向
ModelState
添加错误。 If it returns true
, then you have a valid date and time which you can then compare to DateTime.Now
. 如果返回
true
,则您具有有效的日期和时间,然后可以将其与DateTime.Now
进行比较。
So: 所以:
DateTime temp;
if(!DateTime.TryParse(group.GroupDateTime, out temp))
{
this.ModelState.AddError(....);
return /* add action result here */
}
if(temp < DateTime.Now)
{
this.ModelState.AddError(....)
return /* add action result here */
}
...everything else...
UPDATE #1: You should think of changing the properties of Group
to be more strongly-typed, so change GroupDateTime
to DateTime
. 更新#1:您应该考虑将
Group
的属性更改为更强类型的,因此GroupDateTime
更改为DateTime
。 This would also allow you to use the built-in validation attributes such as MaxLengthAttribute
, RequiredAttribute
, etc. 这也将允许您使用内置的验证属性,例如
MaxLengthAttribute
, RequiredAttribute
等。
I would suggest you to use custom validation on your model (Group). 我建议您对模型(组)使用自定义验证。 You could use a CustomAttribute on GroupDateTime property, like below:
您可以在GroupDateTime属性上使用CustomAttribute,如下所示:
[AttributeUsage(AttributeTargets.Property)]
public class FutureDateValidation : ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
DateTime inputDate = (DateTime)value;
if (inputDate > DateTime.Now) {
return ValidationResult.Success;
} else {
return new ValidationResult("Please, provide a date greather than today.", new string[] { validationContext.MemberName });
}
}
}
public class Group {
[FutureDateValidation()]
[DataType(DataType.Date, ErrorMessage = "Please provide a valid date.")]
public DateTime GroupDateTime { get; set; }
}
In order to garantee the datatype validation, you should use the attribute [DataType(DataType.Date)]. 为了保证数据类型验证,您应该使用属性[DataType(DataType.Date)]。 And you can use a client side script to put masks, using, for example, jquery-ui.
而且,您可以使用客户端脚本来放置掩码,例如使用jquery-ui。
Furthermore, you could replace the "no user logged in" with [Authorize] attributes in your controller or action, and the "Unhandled Error" overriding HandleException on a base controller. 此外,您可以用控制器或操作中的[Authorize]属性替换“没有用户登录”,并用“ Unhandled Error”取代基本控制器上的HandleException。
I strongly suggest you to use declarative validation. 我强烈建议您使用声明性验证。 http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.