0% found this document useful (0 votes)
1 views9 pages

Data Annotation

Data validation in ASP.NET Core MVC ensures that user input is valid before processing or storing it in the database, preventing errors and enhancing security. It includes client-side validation for immediate feedback and server-side validation for security, using built-in data annotation attributes to enforce rules. The document outlines the validation flow, provides examples of model, controller, and view implementations, and emphasizes the importance of both client-side and server-side validation.

Uploaded by

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

Data Annotation

Data validation in ASP.NET Core MVC ensures that user input is valid before processing or storing it in the database, preventing errors and enhancing security. It includes client-side validation for immediate feedback and server-side validation for security, using built-in data annotation attributes to enforce rules. The document outlines the validation flow, provides examples of model, controller, and view implementations, and emphasizes the importance of both client-side and server-side validation.

Uploaded by

Aastha Teotia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ASP.

NET Core MVC - Data Validation

What is Data Validation?

Data Validation is the process of checking whether the data entered by


the user is valid before it is processed or stored in the database.

Validation ensures that only correct and meaningful data is accepted by


the application.

Example

 Name should not be empty.

 Age should be between 18 and 60.

 Email should be in a valid format.

 Password should have a minimum length.

 Confirm Password should match Password.

Without validation, users may submit invalid or incomplete data, leading


to incorrect records and application errors.

Why is Validation Required?

 Prevents invalid data entry.

 Improves application security.

 Enhances user experience.

 Reduces runtime errors.

 Ensures data consistency.

Types of Validation

1. Client-Side Validation

 Performed in the browser.

 Uses JavaScript and jQuery Validation.

 Faster because no request is sent to the server.

 Gives immediate feedback to the user.

Example: If the Name field is empty, the error is displayed immediately


without submitting the form.
2. Server-Side Validation

 Performed on the server.

 Executed after the form is submitted.

 Cannot be bypassed.

 More secure than client-side validation.

Example:

if([Link])

// Save data

else

// Display validation errors

Data Annotation Attributes

[Link] Core MVC provides built-in validation attributes.

Attribute Purpose

[Required] Field cannot be empty

Specifies minimum and maximum


[StringLength]
length

[MinLength] Minimum number of characters

[MaxLength] Maximum number of characters

[Range] Specifies numeric range

[EmailAddress] Validates email format

[Phone] Validates phone number

[Url] Validates URL

[Compare] Compares two properties


Attribute Purpose

[RegularExpressi
Custom validation pattern
on]

[DataType] Specifies the data type

[Display] Friendly display name

Frequently Used Validation Attributes

Required

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

public string Name { get; set; }

The field cannot be left blank.

StringLength

[StringLength(20, MinimumLength=3)]

public string Name { get; set; }

Accepts between 3 and 20 characters.

Range

[Range(18,60)]

public int Age { get; set; }

Age must be between 18 and 60.

EmailAddress

[EmailAddress]

public string Email { get; set; }

Accepts only valid email addresses.

Compare
[Compare("Password")]

public string ConfirmPassword { get; set; }

Checks whether both passwords are identical.

RegularExpression

[RegularExpression(@"^[0-9]{10}$")]

public string Mobile { get; set; }

Accepts only a 10-digit mobile number.

Validation Flow

User Opens Form

User Enters Data

Clicks Submit

Client-Side Validation

If Valid

Request Sent to Server

Server-Side Validation

[Link]

Yes → Save Data

No → Display Errors
Step 1: Model

Models/[Link]

using [Link];

namespace [Link]

public class Register

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

public string Name { get; set; }

[Required(ErrorMessage = "Email is required")]

[EmailAddress(ErrorMessage = "Invalid Email")]

public string Email { get; set; }

[Required]

[Range(18,60, ErrorMessage = "Age must be between 18 and 60")]

public int Age { get; set; }

[Required]

[StringLength(20, MinimumLength = 6,

ErrorMessage = "Password must contain 6 to 20 characters")]

[DataType([Link])]

public string Password { get; set; }

[Required]

[Compare("Password", ErrorMessage = "Passwords do not match")]

[DataType([Link])]

public string ConfirmPassword { get; set; }

Step 2: Controller

Controllers/[Link]
using [Link];

using [Link];

namespace [Link]

public class HomeController : Controller

public IActionResult Register()

return View();

[HttpPost]

public IActionResult Register(Register model)

if ([Link])

[Link] = "Registration Successful";

return View();

return View(model);

} }

Step 3: View

Views/Home/[Link]

@model [Link]

<h2>User Registration Form</h2>

<form asp-action="Register" method="post">

<div>
<label>Name</label><br />

<input asp-for="Name" />

<span asp-validation-for="Name" style="color:red"></span>

</div>

<br /> <div>

<label>Email</label><br />

<input asp-for="Email" />

<span asp-validation-for="Email" style="color:red"></span>

</div> <br />

<div>

<label>Age</label><br />

<input asp-for="Age" />

<span asp-validation-for="Age" style="color:red"></span>

</div>

<br />

<div>

<label>Password</label><br />

<input asp-for="Password" />

<span asp-validation-for="Password" style="color:red"></span>

</div>

<br />

<div>

<label>Confirm Password</label><br />

<input asp-for="ConfirmPassword" />

<span asp-validation-for="ConfirmPassword"
style="color:red"></span>

</div>

<br />
<button type="submit">Register</button>

</form>

@if([Link] != null)

<h3 style="color:green">@[Link]</h3>

@section Scripts

@{

await [Link]("_ValidationScriptsPartial");

Output

Valid Input

 Name: Rahul

 Email: rahul@[Link]

 Age: 25

 Password: abc12345

 Confirm Password: abc12345

Output:

Registration Successful

Invalid Input

 Name: (Blank)

 Email: abc

 Age: 15

 Password: 123
 Confirm Password: 456

Output:

Name is required.

Invalid Email.

Age must be between 18 and 60.

Password must contain 6 to 20 characters.

Passwords do not match.

Important Points

 Validation attributes are placed on model properties.

 [Link] checks whether all validations have passed.

 asp-validation-for displays field-specific validation messages.

 _ValidationScriptsPartial enables client-side validation.

 Always perform server-side validation even if client-side validation is


enabled.

You might also like