0

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);
    }
4
  • Have you ever try to parse your GroupDateTime to DateTime and compare it with DateTime.Now or something? Commented Mar 13, 2015 at 12:53
  • yes I did, I tried to use if (group.GroupDateTime < DateTime.Now) { //err} Commented Mar 13, 2015 at 12:58
  • From you question is sounds like group.GroupDateTime is a string (is this correct?), so that comparison won't work. You need to convert the string to a DateTime first. You should at least do this to determine if you're working will a valid date and time. Commented Mar 13, 2015 at 13:05
  • Yes correct, I will get that part done first. Commented Mar 13, 2015 at 13:13

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Ah! of course, that worked very nice. I never knew how to implement the Custom validation, so thank you for that. I will also work in the [Authorize] attributes.
Great video about ASP.Net MVC Security: pluralsight.com/training/…
1

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.

3 Comments

I've tried to implement this here, and received errors of cannot convert System Time to String. Any thoughts?
Are you sure that the string being passed in to the GroupDateTime is a valid DateTime? If not, then adding validation to your method will capture this and you should add extra validation on the client-side to ensure a correct DateTime is entered. Try changing the UI control to only allow a date/time.
I will continue to try and find multiple ways to go after this. That was the first problem I encountered. Validation took care of this. Thank you @MotoSV

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.