ASP.Net Core MVC: USA Phone and Fax Validation using RegularExpression and Data Annotation attribute

on Jun 20, 2022 02:17 AM

I have requirement that store contact no and fax no of us client.

how can i validate the input from data model using data annotation or regex in ASP.Net Core?

i want to validate USA Contact no and Fax at this class. USA formats like xxx-xxx-xxxx. how can i validate through data annotation or regex?

Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Jun 20, 2022 05:48 AM

Hi pandeygolu420...,

Use the regular expression [0-9]{3}-[0-9]{3}-[0-9]{4}.


public class PersonModel
    [Display(Name = "Phone:")]
    [Required(ErrorMessage = "Phone Number is required")]
    [RegularExpression("^[0-9]{3}-[0-9]{3}-[0-9]{4}$", ErrorMessage = "Invalid Phone")]
    public string PhoneNumber { get; set; }


public class HomeController : Controller
    // GET: Home
    public IActionResult Index()
        return View();

    public IActionResult Index(PersonModel person)
        return View();


@model Phone_Validation_Core_MVC.Models.PersonModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        .error { color: red; }
    <form asp-action="Index" asp-controller="Home" method="post">
        <label asp-for="PhoneNumber" class="control-label"></label>
        <input asp-for="PhoneNumber" class="form-control" />
        <span asp-validation-for="PhoneNumber" class="error"></span>
        <br />
        <input type="submit" value="Submit" />