简体   繁体   中英

Date input validation asp.net

Working in visual studio and have the current code in my controller class called GroupController. On the groups page, I can create a new group. The user will then enter String values for groupName, groupAssignment, groupLocation, and 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 . If that returns false, then add an error to ModelState . If it returns true , then you have a valid date and time which you can then compare to 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 . This would also allow you to use the built-in validation attributes such as MaxLengthAttribute , RequiredAttribute , etc.

I would suggest you to use custom validation on your model (Group). You could use a CustomAttribute on GroupDateTime property, like below:

[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)]. And you can use a client side script to put masks, using, for example, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM