Reputation: 325
In a newly created MVC project, in the Account Register page, if I don't fill in any information and click Register button, I will see
•The User name field is required.
•The Password field is required.
Where are these coming from ?
Upvotes: 2
Views: 179
Reputation: 7605
The actual message string is stored in a MvcHtmlString
object in System.Web.Mvc.ModelStateDictionary.
It is the return value on the ValidationExtensions
method called by the ValidationMessageFor()
helper method that is invoked in the view.
Upvotes: 2
Reputation: 1762
If you take a look at the Register ActionResult (in AccountController.cs)
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid) // here it will check it lal
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
You see the ModelState.IsValid, basicly it checks or the model has any validations issues.
The model can be found in AccountModels
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
As you can see they both got a require tag so they will return false and display next to it that it is required (when it is not filled in)
EDIT: Since you want to know why it is that text and not some other text, it is the default text so ask microsoft :), anyway you can modify the text as you like by adding the ErrorMessage parameter to the Required tag.
Example:
[Required(ErrorMessage = "Hey you forgot me!")]
Upvotes: 4