Home > Mobile >  Asp.net Web api 6: Use ValidationAttribute for a unique userName
Asp.net Web api 6: Use ValidationAttribute for a unique userName

Time:07-02

I do not have much code here But I want to create my own validation for username that will not have duplicates.

Model:

[Table("User")]
public partial class User
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();
    [Column("userName")]
    [StringLength(200)]
    [AllValidation(ErrorMessage = "foo")]
    [Required(ErrorMessage = "Username is a required field")]
    public string UserName { get; set; } = null!;
    [StringLength(50, MinimumLength = 3, ErrorMessage = "The password should be between 3 characters to 50")]
    [Required(ErrorMessage = "Password is a required field")]
    public string Password { get; set; } = null!;
    //[Column(TypeName = "date")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}")]

    public DateTime? LastLogin { get; set; }
    public string? Token { get; set; }
}

ValidationAttribute:

public class AllValidationAttribute : ValidationAttribute
{
    private readonly TalkBackDbContext _context;
    

    public AllValidationAttribute(TalkBackDbContext context)
    {
        _context = context;
    }
    public override string FormatErrorMessage(string name)
    {
        return _context.Users.SingleOrDefault(x => x.UserName == name)!.ToString()!;
    }
}

I get an error when I try to insert ErrorMessage into an attribute

this is the error:

enter image description here

CodePudding user response:

you can do this.

remove it from constructor and override IsValid method.

    public class AllValidationAttribute : ValidationAttribute
    {
       private string username;
       
       protected override ValidationResult IsValid(object value, 
        ValidationContext validationContext)
       {
           var _context = (TalkBackDbContext )validationContext
                      .GetService(typeof(TalkBackDbContext ));
          username = value.ToString();
          
         
          if(!_context.Users.Any(cus => cus.UserName == value.ToString()))
          {
            return ValidationResult.Success;
          }
          else
          {
            return new ValidationResult
                ("Unique Name expected"   value.ToString());
          } 
       }

       public override string FormatErrorMessage(string name)
       {
         return "Expected Uniquename"   username;
       }
   }

    
  • Related