Home > Net >  ASP.NET Core MVC Unique Phone Number and SSN
ASP.NET Core MVC Unique Phone Number and SSN

Time:10-03

I am working with ASP.NET Core MVC Identity and I want to add a unique field for both Phone Number and SSN (National ID). Since I am working with .NET Identity I could not found a controller that is scaffolded after scaffolding .NET Identity.

As far as I know, there are two ways to solve this. One by doing a remote-validator and the other by implementing a function in the Controller. I would search inside the DB for existing Phone Numbers and SSN then if True return a JSON result showing an error message. But, how would I do this ? or are there any more efficient solutions ?

Folder Structure for Identity:

Register.cshtml custom fields snippets:

    [Required(ErrorMessage ="National ID is a required field")]
    [DataType(DataType.Text)]
    [Display(Name = "Nationa ID")]
    [StringLength(10, MinimumLength =10, ErrorMessage ="National ID must be 10 digits")]
    [RegularExpression("(^[0-9]*)(^[12].*)", ErrorMessage = "National ID must be numeric")]
    //TODO: make it unique
    public string NationalId { get; set; }

    [Required(ErrorMessage ="Phone Number is a required field")]
    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Phone Number")]
    [RegularExpression(@"^((?:[ ?0?0?966] )(?:\s?\d{2})(?:\s?\d{7}))$", ErrorMessage = "Not a valid phone number")] 
    //TODO: Make it unique
     public string PhoneNumber { get; set; }

Thanks

CodePudding user response:

Consider using [Remote(action: "Action Name", controller: "Controller Name",AdditionalFields = "Your additional parameters of the action", ErrorMessage = "Message displayed in form after validation")] above the validating property.

Please note that the value of the property will be used as the first parameter in you action.

Then in the controller you point the attribute to add your action to get the json result from your database

[AcceptVerbs("Get", "Post")]
    public async Task<IActionResult> ActionName(string phoneNumber)
    {
        // Do Database checking
        {
            // If value already exists
            return Json(false);
        }
        //If unique value
        return Json(true);
    }

finally you should include folloing scripts at your View or _Layout.cshtml

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

For a more detailed atricle please check this one here

  • Related