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

pandeygolu4200
 
on Jun 20, 2022 02:17 AM
Sample_206873.zip
199 Views

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
dharmendr
 
on Jun 20, 2022 05:48 AM

Hi pandeygolu420...,

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

Model

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; }
}

Controller

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

    [HttpPost]
    public IActionResult Index(PersonModel person)
    {
        return View();
    }
}

View

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

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        .error { color: red; }
    </style>
</head>
<body>
    <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" />
    </form>
</body>
</html>

Screenshot