In the previous posts we
saw on how to create an Asp.Net Core MVC
controller and views to View, Edit and Delete detail using Entity Framework Core. In this post we will see on how to add Model
validations which will be applied to the Views to validate data before we
Add/Delete details to the database.
Asp.Net Core makes it easy to validate entities, all we need to do is to add the validation properties to the Model class and Asp.Net Core takes care of applying the validations in the view automatically. In the previous version of Asp.Net MVC we had to validate the user input fields in the View layer using Validation controls like Required Field validator, Range Validator, Regular expression validator etc, but Asp.Net Core takes care of this for us.
In this post we shall see on how to validate the User entity by adding validations to the Users model class and how it gets automatically applied to the View layer, to start let us open the Users Model class and apply the following validations.
public partial class Users
Asp.Net Core makes it easy to validate entities, all we need to do is to add the validation properties to the Model class and Asp.Net Core takes care of applying the validations in the view automatically. In the previous version of Asp.Net MVC we had to validate the user input fields in the View layer using Validation controls like Required Field validator, Range Validator, Regular expression validator etc, but Asp.Net Core takes care of this for us.
In this post we shall see on how to validate the User entity by adding validations to the Users model class and how it gets automatically applied to the View layer, to start let us open the Users Model class and apply the following validations.
public partial class Users
{
public int UserId { get; set; }
[StringLength(50)]
[Required]
public string FirstName { get; set; }
[StringLength(50)]
[Required]
public string LastName { get; set; }
[StringLength(10)]
[RegularExpression(@"^[0-9]{10}")]
[Required]
public string Phone { get; set; }
[StringLength(50)]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
[Required]
public string Email { get; set; }
[StringLength(100)]
[Required]
public string Address { get; set; }
public string AttachmentPath { get; set; }
The [Required] attribute makes sure that the user enters value for this property / field. The [StringLength(50)] attribute validates that the user inputs only upto 50 characters in this field. The [RegularExpression] attribute validates the users input to this field against the specified Regular expression.
Build and run the project, try to edit any user and try to enter any invalid value for the fields which do not match the validations in the Model, you can see that appropriate validation messages are displayed and the user is not allowed to save the User details without correcting the validation errors.
No comments:
Post a Comment