How to make custom validation with Tag Helper?

Dondon510 261 Reputation points
2022-07-26T06:15:54.453+00:00

How to make custom validation with Tag Helper? (ASP MVC NET6)

I have this Registration Class like below:

public class Registration  
{          
        [Required]  
        [EmailAddress]  
        [Display(Name = "User Email Address")]  
        public string userEmail { get; set; } = "";  
  
  
  
I need to check to a user table (Users), if the emailAddress already exists or not  
  
  
internal static bool IsEmailExists(string emailAddress)  
bool isExists = false;  
...  
...  
  
return isExists  
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Xinran Shen - MSFT 2,091 Reputation points
    2022-07-26T09:08:25.693+00:00

    Hi, @Dondon510

    I suggest you to use RemoteAttribute to achieve this, you can refer to this simple demo:

    remote method

    [AcceptVerbs("Get", "Post")]  
        [AllowAnonymous]  
        public async Task<IActionResult> IsEmailInUse(string email)  
        {  
            //check if the emailAddress already exists or not in database  
    
            var user =await _dbContext.users.Where(x => x.Email == email).FirstOrDefaultAsync();  
            if (user == null)  
            {  
                return Json(true);  
            }  
            else  
            {  
                return Json($"Email {email} is already in use");  
            }  
        }  
    

    Then add remote attribute in your model

             [Required]  
             [EmailAddress]  
             [Display(Name = "User Email Address")]  
             [Remote(action:"IsEmailInUse",controller:"Home")]  
             public string userEmail { get; set; }  
    

    Now, When you type email in <input/>,It will check if the emailAddress already exists or not

    224803-image.png

    -------------------------------------------------------------------------------------------------------------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Xinran Shen


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.