ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalEC-332Mvc Validation
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    EC-332

    Enterprise Application Development

    Progress0 / 37 done
    Topics37
    1Microsoft technology history2Introduction to .NET and its architecture3Concept of MSIL, CLR, CLS, CTS
    4Managed and Unmanaged Code5.Net Assembly6Introduction to C# fundamentals7Boxing and Unboxing8Implementing multi-tier architecture
    9SQL Injection, parameterized queries10Usage of data set, Data adapter and command builder in disconnected model
    11Multicast delegates12Introduction to windows forms13HTML
    14javascript and its data types, variables, functions15Debugging javascript using Firebug
    16Browser's Object (BOM), Document Object Model
    17Jquery effects
    18LINQ to Objects, LINQ to SQL19Query syntax, Operations (projection, filtering and join) using Linq Queries
    20The entity data model, CSDL21Eager vs lazy loading, POCO classes, DBContext API22Querying entity data models23Introduction to ASP.NET MVC24MVC application structure, Controllers overview25Action Methods, Parameterized action methods26Introduction to razor syntax27Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28Data annotations, Client and Server Side Validation29Validation and model binding, Validation and model state30MVC Membership, Authorization and security
    31SOAP, WSDL32Service contract, Data contract, XML, WCF bindings33ABC of WCF, Restful services34Consuming rest services (CRUD operations) using Jquery AJAX and JSON35Introduction to web API36Example of web API using CRUD Example37MVC routing
    6 min read
    Topic 28 of 37
    Topic Study Note Illustration
    28

    Data annotations, Client and Server Side Validation

    In the context of web development, especially when building forms in ASP.NET Core and other similar frameworks, data annotations are used to enforce validation rules for user...

    In the context of web development, especially when building forms in ASP.NET Core and other similar frameworks, data annotations are used to enforce validation rules for user inputs. These rules can be validated both on the client side (in the browser) and server side (on the server where the data is processed). Let's go through each concept in detail:

    1. Data Annotations:

    Data annotations are attributes that you can apply to your model properties in C# to specify rules for data validation. These attributes help define constraints like "required", "range", "length", "pattern", etc., without having to write custom validation logic manually.

    Data annotations are part of the System.ComponentModel.DataAnnotations namespace and can be used in conjunction with model classes in ASP.NET to enforce validation rules for user inputs.

    Common Data Annotations:

    • [Required]: Ensures that a field is not left empty.

      [Required(ErrorMessage = "Name is required")]
      public string Name { get; set; }
      
    • [StringLength]: Specifies the minimum and maximum length for a string field.

      [StringLength(50, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 50 characters")]
      public string Name { get; set; }
      
    • [Range]: Defines a range of acceptable values for numeric types.

      [Range(18, 99, ErrorMessage = "Age must be between 18 and 99")]
      public int Age { get; set; }
      
    • [EmailAddress]: Ensures the field is a valid email address.

      [EmailAddress(ErrorMessage = "Invalid email address")]
      public string Email { get; set; }
      
    • [RegularExpression]: Validates a string against a regular expression.

      [RegularExpression(@"^\d{10}$", ErrorMessage = "Phone number must be 10 digits")]
      public string PhoneNumber { get; set; }
      
    • [Compare]: Validates that two fields are equal (commonly used for password confirmation).

      [Compare("Password", ErrorMessage = "Passwords do not match")]
      public string ConfirmPassword { get; set; }
      

    These annotations are useful for ensuring that data entered by the user meets certain criteria and helps in preventing invalid data from being stored in a database or processed further.


    2. Client-Side Validation:

    Client-side validation happens in the user's browser before the data is sent to the server. It improves the user experience by providing immediate feedback on form inputs. In ASP.NET Core, data annotations can also be used with JavaScript to perform client-side validation.

    When you use data annotations on model properties, ASP.NET Core automatically generates the necessary HTML and JavaScript for client-side validation. This is typically done using the jQuery Validation library, which is included in ASP.NET Core MVC by default.

    How Client-Side Validation Works:

    1. The user fills out the form and submits it.
    2. JavaScript (via jQuery Validation) automatically checks the inputs based on the data annotations (like Required, EmailAddress, etc.).
    3. If validation fails, the form won’t be submitted, and the user sees an error message on the page.

    Example of Client-Side Validation:

    For the following model:

    public class UserModel
    {
        [Required(ErrorMessage = "Name is required")]
        [StringLength(50, MinimumLength = 2, ErrorMessage = "Name must be between 2 and 50 characters")]
        public string Name { get; set; }
    
        [EmailAddress(ErrorMessage = "Invalid email address")]
        public string Email { get; set; }
    }
    

    In the Razor View (HTML Form), you can use the following to enable client-side validation:

    @model UserModel
    
    <form asp-action="Submit" method="post">
        <div>
            <label for="Name">Name</label>
            <input type="text" asp-for="Name" />
            <span asp-validation-for="Name"></span>
        </div>
        
        <div>
            <label for="Email">Email</label>
            <input type="text" asp-for="Email" />
            <span asp-validation-for="Email"></span>
        </div>
        
        <button type="submit">Submit</button>
    </form>
    
    @* Enable client-side validation *@
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    In this example, asp-for generates the appropriate HTML, and asp-validation-for binds validation error messages. The validation happens instantly in the browser when the user interacts with the form fields.


    3. Server-Side Validation:

    Server-side validation occurs when the data is submitted to the server. After client-side validation, the server also checks the data to ensure it is valid, typically before saving it to a database. Server-side validation is essential because client-side validation can be bypassed (e.g., by disabling JavaScript or using tools to manipulate HTTP requests), so you cannot rely solely on it for security.

    ASP.NET Core automatically performs server-side validation based on the data annotations you've applied to your model. This validation happens when the form is submitted and before the data is processed or stored.

    Example of Server-Side Validation:

    In your controller, you can check if the model state is valid using ModelState.IsValid:

    [HttpPost]
    public IActionResult Submit(UserModel model)
    {
        if (ModelState.IsValid)
        {
            // Proceed with saving the data or further processing
            return RedirectToAction("Success");
        }
        
        // If the model is invalid, return to the form with error messages
        return View(model);
    }
    

    In this case, if any validation rule (e.g., Required, EmailAddress) fails, the form will not submit successfully, and the user will be redirected back to the form with error messages. These error messages are displayed using the asp-validation-for helper in the Razor view.


    Summary:

    • Data Annotations: Attributes like [Required], [StringLength], [EmailAddress], etc., applied to model properties to specify validation rules.

    • Client-Side Validation: Validation happens in the user's browser before the form is submitted. ASP.NET Core automatically generates the necessary JavaScript for validation when data annotations are used.

    • Server-Side Validation: Validation occurs on the server once the data is submitted. This step is necessary for ensuring the integrity of the data, as client-side validation can be bypassed.

    Both client-side and server-side validation are crucial for providing a good user experience and ensuring data integrity and security in your application.

    ← Previous topic 27
    Code expressions, Code Blocks, Implicit Vs Explicit Code Expression
    Next topic 29 →
    Validation and model binding, Validation and model state

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.0kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Enterprise Application Development