ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Data annotations, Client and Server Side Validation
    Enterprise Application DevelopmentTopic 28 of 37

    Data annotations, Client and Server Side Validation

    6 minread
    1,005words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,005
      Code examples0
      DifficultyIntermediate