Adding Validations in the Contact Number Field using ASP.NET Core
Image by Elliner - hkhazo.biz.id

Adding Validations in the Contact Number Field using ASP.NET Core

Posted on

When building a web application, it’s crucial to ensure that user input data is accurate and valid. One of the most critical fields that require validation is the contact number field. In this article, we’ll explore how to add validations in the contact number field using ASP.NET Core.

Why Validate Contact Numbers?

A contact number is a crucial piece of information for various business purposes, such as customer communication, order tracking, and marketing campaigns. Invalid or fake contact numbers can lead to:

  • Failed communication attempts
  • Inaccurate customer data
  • Wasted resources
  • Decreased customer satisfaction
  • Loss of business opportunities

By adding validations to the contact number field, you can ensure that only valid and accurate numbers are accepted, reducing the risk of errors and improving overall data quality.

ASP.NET Core Validation Overview

ASP.NET Core provides a robust validation framework that allows developers to validate user input data. The framework uses the following components:

  • IValidatableObject: An interface that defines a method to validate an object.
  • ValidationAttribute: A base class for validation attributes that define validation rules.
  • ValidationResult: A class that represents the result of a validation operation.

In ASP.NET Core, you can use data annotations to decorate model properties with validation attributes. The framework will then automatically validate the input data against these attributes.

Adding Validations to the Contact Number Field

Let’s create a simple ASP.NET Core application to demonstrate how to add validations to the contact number field.

Create a new ASP.NET Core Web Application project in Visual Studio, and add a new model class called Contact.cs:


using System.ComponentModel.DataAnnotations;

public class Contact
{
    [Required]
    [Display(Name = "Contact Number")]
    [Phone(ErrorMessage = "Invalid phone number.")]
    public string PhoneNumber { get; set; }
}

In the above code, we’ve added three validation attributes to the PhoneNumber property:

  • Required: Specifies that the property is required.
  • Display: Specifies the display name for the property.
  • Phone: Specifies that the property should be a valid phone number.

Next, create a new view model class called ContactViewModel.cs:


public class ContactViewModel
{
    public Contact Contact { get; set; }
}

In the view model, we’ve added a property called Contact of type Contact.

Create a new Razor Page called Contact.cshtml.cs:


using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

public class ContactModel : PageModel
{
    [BindProperty]
    public ContactViewModel ContactViewModel { get; set; }

    public void OnGet()
    {
    }

    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // Process the contact data
        return RedirectToPage("/Success");
    }
}

In the Razor Page, we’ve added a BindProperty attribute to the ContactViewModel property to enable model binding. We’ve also added a OnPost method to handle the form submission.

Create a new Razor Page called Contact.cshtml:


@page
@model ContactModel

<form method="post">
    <label asp-for="ContactViewModel.Contact.PhoneNumber"></label>
    <input asp-for="ContactViewModel.Contact.PhoneNumber" />
    <span asp-validation-for="ContactViewModel.Contact.PhoneNumber" class="text-danger"></span>
    <br />
    <button type="submit">Save</button>
</form>

In the Razor Page, we’ve added a form with a label, input field, and validation message for the PhoneNumber property. We’ve also added a submit button to handle the form submission.

Custom Validation Attributes

In some cases, you may need to add custom validation rules that are not provided by ASP.NET Core’s built-in validation attributes. Let’s create a custom validation attribute to validate the contact number format.

Create a new class called PhoneValidationAttribute.cs:


using System.ComponentModel.DataAnnotations;

public class PhoneValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var phoneNumber = value as string;
        if (string.IsNullOrEmpty(phoneNumber))
        {
            return true;
        }

        var phoneNumberRegex = @"^(\+)?(1)?[-. ]?(\(?(\d{3})\)?[- ]?){0,1}(\d{3})[-. ]?(\d{4})$";
        if (Regex.IsMatch(phoneNumber, phoneNumberRegex))
        {
            return true;
        }

        return false;
    }
}

In the above code, we’ve created a custom validation attribute called PhoneValidationAttribute. The attribute uses a regular expression to validate the contact number format.

Update the Contact.cs model to use the custom validation attribute:


using System.ComponentModel.DataAnnotations;

public class Contact
{
    [Required]
    [Display(Name = "Contact Number")]
    [PhoneValidation(ErrorMessage = "Invalid phone number format.")]
    public string PhoneNumber { get; set; }
}

Server-Side Validation

In addition to client-side validation, it’s essential to perform server-side validation to ensure that the input data is valid.

In the Contact.cshtml.cs Razor Page, we’ve added a check for model state validity in the OnPost method:


public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    // Process the contact data
    return RedirectToPage("/Success");
}

If the model state is invalid, the method returns the page with validation errors. If the model state is valid, the method processes the contact data and redirects to a success page.

Client-Side Validation

ASP.NET Core provides client-side validation using the jQuery Unobtrusive Validation library. To enable client-side validation, add the following scripts to the _Layout.cshtml file:


<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"></script>

In the Contact.cshtml Razor Page, we’ve added the following code to enable client-side validation:


<script>
    $.validator.setDefaults({
        submitHandler: function () {
            debugger;
        }
    });
</script>

The above code sets the default submit handler for the jQuery Unobtrusive Validation library.

Conclusion

In this article, we’ve explored how to add validations to the contact number field using ASP.NET Core. We’ve covered the importance of validation, ASP.NET Core’s validation framework, and how to add custom validation attributes. We’ve also demonstrated how to perform server-side and client-side validation.

By following these steps, you can ensure that your contact number field accepts only valid and accurate numbers, reducing the risk of errors and improving overall data quality.

Validation Attribute Description
Required Specifies that the property is required.
Phone Specifies that the property should be a valid phone number.
PhoneValidation Specifies a custom validation rule for phone numbers.

Remember to always validate user input data to ensure the accuracy and reliability of your application’s data.

Frequently Asked Question

Get the lowdown on adding validations in the Contact number field using ASP.NET Core!

Why do I need to add validation to my Contact number field in ASP.NET Core?

Adding validation to your Contact number field is crucial to ensure that users enter a valid phone number, which is essential for communication and data accuracy. Without validation, your database might be filled with incorrect or malformed phone numbers, leading to issues with communication and ultimately affecting your business. By implementing validation, you can guarantee that only valid phone numbers are accepted, making your data more reliable and efficient.

What are the common validation rules I can apply to the Contact number field in ASP.NET Core?

Some common validation rules you can apply to the Contact number field include: checking for a minimum and maximum length, ensuring the number starts with a specific digit or prefix, validating the format (e.g., 123-456-7890), and restricting certain characters or patterns. You can also use regular expressions to match specific phone number formats, making it even more flexible and customizable.

How do I add validation to the Contact number field using ASP.NET Core Data Annotations?

To add validation using ASP.NET Core Data Annotations, you can decorate your Contact number property with validation attributes, such as [Required], [RegularExpression], or [StringLength]. For example, you can use [RegularExpression(@"^(\d{3})-?(\d{3})-?(\d{4})$", ErrorMessage = "Invalid phone number format.")] to validate a phone number in the format XXX-XXX-XXXX.

Can I use FluentValidation to validate the Contact number field in ASP.NET Core?

Yes, you can use FluentValidation to validate the Contact number field in ASP.NET Core. FluentValidation is a popular validation library that provides a more flexible and customizable way of defining validation rules. You can create a custom validator class that inherits from AbstractValidator<Contact> and define rules for the Contact number field using the RuleFor method.

How do I display validation errors for the Contact number field in ASP.NET Core?

To display validation errors for the Contact number field, you can use the ModelState dictionary to access the error messages. You can then display the error messages using HTML helpers, such as @Html.ValidationMessageFor, or by using JavaScript to update the UI dynamically. Make sure to include the asp-validation-for attribute in your HTML element to enable client-side validation.

Leave a Reply

Your email address will not be published. Required fields are marked *