Required Validation in MVC

Because you need the customer to give you his fi rst and last name, you can decorate the FirstName and LastName properties of the Order model with the Required attribute:

[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required(ErrorMessage = "Nick name is required")]
public string NickName { get; set; }

The attribute raises a validation error if either property value is null or empty. (You will learn how to deal with validation errors in just a bit.)
Like all the built-in validation attributes, the Required attribute delivers both server-side and client side validation logic (although internally, it is another, different component in the MVC framework that delivers the client-side validation logic for the attribute through a validation adapter design).
With the attribute in place, if the customer tries to submit the form without providing a last name, he’ll see the default error in Figure.

However, even if the customer does not have JavaScript enabled in his browser, the validation logic will catch an empty name property on the server, too. Assuming your controller action is implemented correctly (which I promise I will talk about in just a bit), the user will still see the error message in the preceding screenshot.

Tagged . Bookmark the permalink.

Leave a Reply