Monday, May 27, 2019

Model Validation in Asp.Net Core

Validation is an important part of any application which accepts inputs from users, the data entered by the user needs to be validated for integrity before it is saved in the database. Validations could be on the type of data like int, string, decimal etc. On the format of the data like email, SSN, Phone Number etc. Also we might need custom validation specific to the application.

Asp.Net Core MVC Model validation provides us an easy and effective way to validate user input, using Model validation we can specify the validation parameters in the Model object and the framework will take care of validating the inputs in the View.

Asp.Net Core provides a set if built-in basic validation attributes which can be added to the Model properties to validate them, for example the [Required] validation attribute makes sure that the user enters a value for the corresponding field in the View. The [StringLength(50)] Attribute makes sure that the user enters no more than 50 characters for the field in the View.

We can also use combination of these attributes to impose multiple validations on a field, the below validation makes sure that the user has to enter a value for FirstName and also makes sure that he enters no more than 50 characters.

        [StringLength(50)]
        [Required(ErrorMessage = "Please enter First Name.")]
        public string FirstName { get; set; }

To handle custom pattern validations, we have a RegularExpression attribute, which takes a regular expression and validates the input to match the pattern specified in the Regular Expression. The below validation makes sure that the user enters only Numbers in the Phone field.

[
RegularExpression(@"^[0-9]{10}")] 
public string Phone { get; set; }

In the controller, we can check the ModelState to make sure that the Model validations were successful. When ModelState.IsValid is true the validations are successful and we can go ahead and save the model to the database.

       
if (ModelState.IsValid)
       {
           // Perform database operations using Model object.
       }


Search Flipkart Products:
Flipkart.com

1 comment:

Anonymous said...

Kemudian bandar membayar kepada pemain yang kartunya lebih besar dari pada kartu bandar sebesar jumlah taruhan yang di pasang oleh pemain tersebut.
asikqq
dewaqq
sumoqq
interqq
pionpoker
bandar ceme terbaik
hobiqq
paito warna
bocoran sgp
data hk