This current project I am trying to get a registration form and pass it through validation. I am pretty new to C# and ASP.NET MVC4. I am trying to prevent a user being added to a collection of the incoming Post data is invalid. Here is my controller code, followed by my User class with rules using System.ComponentModel.DataAnnotations
If the data is invalid then I want to throw a custom error (i have not begun implementing this just yet).
Controller:
[HttpPost]
public ActionResult Confirm(FormCollection form)
{
string firstName = form["textFirstName"];
string lastName = form["textLastName"];
string email1 = form["textEmail"];
string password1 = form["passwordPW1"];
User newUser = new User { fName = firstName, lName = lastName, email = email1, password = password1 };
if (ModelState.IsValid)
{
_users.Add(newUser);
}
return RedirectToAction("Login", "Countdown");
}
Model:
public class User
{
[Required]
[StringLength(50, MinimumLength = 1)]
public String fName { get; set; }
[StringLength(50)]
public String lName { get; set; }
[Required]
[RegularExpression(@"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$")]
public String email { get; set; }
[Required]
[StringLength(50, MinimumLength = 4)]
public String password { get; set; }
}
Confirm(User data)and make sure the field names in HTML match the property names (which you can do with@Html.TextBoxFor()etc). Then your validation attributes will work.