0% found this document useful (0 votes)
26 views35 pages

Unit 4

Uploaded by

nkpatel2355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views35 pages

Unit 4

Uploaded by

nkpatel2355
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

ASP.

NET Core-I
DU # 2101CS511

Unit-4
Validations/Data
Annotations, Areas
& Model Binding
Prof. Naimish R Vadodariya
Computer Engineering Department
Darshan University, Rajkot
[email protected]
8866215253
Validations with Data
Annotation
Why Validation?
 When we developed any type of application such as web-based or desktop based, in both the
application one is the key part of development is Data Validation or Form Validation.
 These validations always ensure us that user fills the correct form of data into the application
so that we can process that data and submit.
 Normally users always fill the data with necessary information and submit it or select it. But,
sometimes the user make some mistakes while filling or selecting data.
 In this case, form validation is required to ensure that the user always provides the required
information in the proper format which is required for the successful submit the details.
 The field value is required.
 Please enter valid email
 Please Enter Age between 1 to 120 etc.
 This type of message known as user defined validations messages.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 3
Why Validation?
 When a user fills the data in the forms, applications validate those data either it is correct or
not.
 If it is correct, then application send those data to the server for processing in the
database.
 If it not in correct format, then it throws/displays an error messages providing
information about what corrections need to be done by the user.
 Validation Types/Modes
 Client Side Validation
 Server Side Validation

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 4
Client Side Validation
 Server-Side validation is the most successful and secure validation process. But sometime,
we need to implement client-side validation for the better user experience.
 Normally, this type of validations done by the scripting languages in the client side.
 The most best things of this types of validations is that form submit method is not executed
in this case if validation fails.
 Means, if we implement client-side validation in our application, then server-side method or
process will be invoked only when client-side validation has been passed successfully.
(ModelState.IsValid)
 To implement the Client-side validation, we need to add the proper JavaScript script
reference in the UI or custom code.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 5
Client Side Validation
 jQuery Unobtrusive Validation is one the custom front-end library provided by the
Microsoft on the based of most popular and well known scripting library JQuery validate
plugin.
 We can generate any type of custom data attributes for both server and client side with help
of Asp.Net Core.
 For custom data attribute, JQuery Unobtrusive library simply transfer the server side
validation logic to the client side.
 Following script files are used to apply server side logic validation to client side.
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 6
Model Validation with Data Annotations
 Validation attributes, or more precisely Data Annotations attributes, allow us to specify rules
that the properties in our model should conform to.
 It is one of the ways to implement or configure model validations in the model class
property.
 We can apply DataAnnotations attributes directly to our binding models to indicate the
type of data that’s acceptable.
 We can use Data Annotations by using System.ComponentModel.DataAnnotations
namespace.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 7
Data Annotations attributes
Attribute Description
[Required] Validates that the field isn't null
[Range(min, max)] Validates that the property value falls within a specified range
[RegularExpression(regex
Validates that the property value matches a specified regular expression
)]
[StringLength(max)] Validates that a string property value doesn't exceed a specified length limit
[MinLength(min)] Validates that a collection has at least the min amount of items
[Compare] Validates that two properties in a model match
[EmailAddress] Validates that the property has an email format
[CreditCard] Validates that a property has a valid credit card format

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 8
[Required]

[Required]
public string Name { get; Empty The Name field is required.
set; }
[Required]
[Display(Name="First Name")] Empty The First Name field is required.
public string Name { get; set; }

[Required(ErrorMessage ="Please Enter Empty Please Enter Name


Name")]
public string Name { get; set; }

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 9
[StringLength(max)]

[StringLength(10)]
public string Mobile { get; set; } It will allow user to enter max 10 characters

[Required(ErrorMessage ="Enter Mobile No")]


[StringLength(10)]
It will allow to enter max 10 characters
public string Mobile { get; set; } If field is empty then it will show error message
Enter Mobile No

[StringLength(10, MinimumLength = 3, It will allow to enter max 10 characters


ErrorMessage = "Minimum 3 characters are Here, we have defined MinumumLength
required")] property which will prompt user to enter
public string Mobile { get; set; } minimum 3 characters.
If anyone enters characters less than 3
then it will give error message
Minimum 3 characters are required

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 10
[Range(min, max)]

[Range(1, 5)] Empty The Rating field is required.


public double Rating { get; Characters The field Rating must be a number.
set; } Value outside range The field Rating must be
between 1 and 5.

[Range(1, 5, ErrorMessage = "Enter Range Between 1 to Error Message:


5")] Enter Range Between 1 to 5
public double Rating { get; set; }

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 11
[RegularExpression(regex)]
[RegularExpression("^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]{4}$")]
public string AadharCard { get; set; }

Empty The AadharCard field is required


Invalid value The field AadharCard must match the regular expression '^[2-9]{1}[0-9]{3}\s[0-9]{4}\s[0-9]
{4}$'.
[RegularExpression("^[2-9]{1}[0-9]{3}\\s[0-9]{4}\\s[0-9]
{4}$",
ErrorMessage ="Invalid Aadhar Card No")] Understand Regular Expression
• ^ represents the starting of the string.
public string AadharCard { get; set; } • [2-9]{1} represents the first digit should be any from 2-9.
Error Message • [0-9]{3} represents the next 3 digits after the first digit should
Invalid Aadhar Card No be any digit from 0-9.
• \\s represents white space.
• [0-9]{4} represents the next 4 digits should be any from 0-9.
• \\s represents white space.
• [0-9]{4} represents the next 4 digits should be any from 0-9.
• $ represents the ending of the string.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 12
[MinLength(min)]
Empty The LastName field is required
[MinLength(4)] String Less than 4 characters The field
public string LastName { get; set; } LastName must be a string or array type with a
minimum length of '4'.

[MinLength(4,ErrorMessage = "Minimum 4 characters required")]


public string LastName { get; set; }

String Less than 4 characters Minimum 4 characters required

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 13
[Compare]
[StringLength(10)]
public string Mobile { get; set; }
Empty The MobileFather field is required
[Compare("Mobile")] String does not match 'MobileFather' and
public string MobileFather { get; set; }
'Mobile' do not match.

[Compare("Mobile",
ErrorMessage ="Mobile number does not match")] String does not match Mobile number
public string MobileFather { get; set; } does not match

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 14
[EmailAddress]

[EmailAddress] Empty The Email field is required.


public string Email { get; set; } String does not match The Email field is
not a valid e-mail address.

[EmailAddress(ErrorMessage ="Please Enter Valid Email")]


public string Email { get; set; }

Invalid Email Please Enter Valid Email

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 15
Employee Model
public class EmployeeModel
{

[Required(ErrorMessage = "First Name is Required")]


[Display(Name = "First name")]
public string FirstName { get; set; }

[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }

[Required]
[StringLength(10)]
public string MobileNo { get; set; }

[Required(ErrorMessage = "Enter Valid email")]


[EmailAddress]
public string Email { get; set; }
}

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 16
Employee.cshtml
<div class="form-group col-md-4">
<h3>Employee Registrtion </h3> <hr />
</div>
<div class="form-row">
<form role="form" method="post" asp-controller="Employee" asp-action="Save">
<div class="form-group">
<div class="form-group col-md-4">
<label for="inputCity"><span class="text-danger">*</span>First Name</label>
<input type="text" class="form-control" placeholder="Enter First Name"
asp-for="FirstName">
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="form-group col-md-4">
<label for="inputCity"><span class="text-danger">*</span>Last Name</label>
<input type="text" class="form-control" placeholder="Enter Last Code"
asp-for="LastName">
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
</div>

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 17
Employee.cshtml
<div class="form-group">
<div class="form-group col-md-4">
<label for="inputCity"><span class="text-danger">*</span>Mobile No</label>
<input type="text" class="form-control" placeholder="Enter State Code"
asp-for="MobileNo">
<span asp-validation-for="MobileNo" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="form-group col-md-4">
<label for="inputCity"><span class="text-danger">*</span>Email</label>
<input type="text" class="form-control" placeholder="Enter State Code"
asp-for="Email">
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 18
Example: Employee Registration | Client Side Validation

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 19
Server Side Validation
 Server side validations are required for ensuring that the received data is correct and valid.
 If the received data is valid then we do the further processing with the data.
 In this process, if the data not validated, then a response along with proper error message is
sent back to the client where these messages are shown to the user so that those wrong data
can be rectified.
 Server side validations are important before accessing any information provided by
user.
 User could disable script in his browser or do something else to bypass client-side validation,
in this case server-side validation must required to protect our data from wrong input.
 In Asp.Net Core, the best way to perform the server-side validation is using Model
Validation.
 Microsoft provides us with the abstract validation layer as validation attributes which
contains validation code.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 20
ModelState
 ModelState is a property of controller that is used for validating form in server side.
 ModelState is a collection of name and value pair that was submitted to the server during
post.
 It also contains a collection of error messages for each value submitted.
 ModelState.IsValid property
 ModelState.IsValid property is an inbuilt property which verifies two things:
 Whether the Form values are bound to the Model.
 All the validations specified inside Model class using Data annotations have been passed.
if (ModelState.IsValid)
{
... do something
}
else
{
... do something
}

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 21
Student Model | Without Annotations

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 22
Student Form Design

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 23
Home Controller Save Action Method

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 24
Output

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 25
Output

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 26
Areas
4.3
Introduction: Areas
 Areas provide a way to partition an ASP.NET Core Web app into smaller functional groups,
each with its own set of Razor Pages, controllers, views, and models.
 An area is effectively a structure with better management.
 It allows you to logically partition your application into smaller units, making it easier to
manage and scale larger applications.
 The ASP.NET Core runtime uses naming conventions to create the relationship between these
components.
 Areas are an ASP.NET feature used to organize related functionality into a group as a
separate:
 Namespace for routing.
 Folder structure for views and Razor Pages.
 Using areas creates a hierarchy for the purpose of routing by adding another route parameter,
area, to controller and action or a Razor Page page.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 28
Introduction - Cont..
 When to use Area?
 The app is made of multiple high-level functional components that can be logically separated.
 You want to partition the app so that each functional area can be worked on independently
 For an example, a large enterprise application may have different modules like admin,
finance, HR, marketing, etc. Each of these units have their own area to contain views,
controllers, Razor Pages, and models.

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 29
Adding Areas in project
Add Area in project
 A ASP.NET Core web app using areas, controllers, and views contains the following:
 An Area folder structure.
 Controllers with the [Area] attribute to associate the controller with the area.
 The area route added to Program.cs file.
 An area folder structure:

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 31
Add Area in project - Cont..
 Controllers with the [Area] attribute to associate the controller with the area.

app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}“
);

[Area("Branch")]
public class MST_BranchController : Controller
{

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 32
Steps to add Area in project
 Step 1: Right click on Project  Add New Scoffolded Item

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 33
Steps to add Area in project
 Step 2: Select MVC Area Click on Add

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 34
Steps to add Area in project
 Step 3: Given Name to Area and Click on Add

#2101CS511 (ASP.NET Core-I)  Unit 4 – Validations/Data Annotations, Areas & Model


Prof. Naimish Vadodariya 35

You might also like