Validate when not empty

Dondon510 261 Reputation points
2022-07-28T10:26:19.493+00:00

Still with Tag Helper, We are in User Profile page, this page also include Change password option, the users are able to skip if they don't want to change the password, so the logic is the validation should be run if newPassword not empty!

if I use below:

    [DataType(DataType.Password)]  
    [Display(Name = "New Password")]  
    [StringLength(250, MinimumLength = 6, ErrorMessage = "Minimum 6 character password required")]  
    public string newPassword { get; set; } = "";  

    [NotMapped]  
    [Required(ErrorMessage = "Verify Password required")]  
    [CompareAttribute("newPassword", ErrorMessage = "Password doesn't match.")]  
    [DataType(DataType.Password)]  
    public string verifyPassword { get; set; } = "";  

if users don't want to change their password, then newPassword would be left empty, but it would be still validated here.

any body can give me an advice, how to deal with this?

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Answer accepted by question author
  1. Anonymous
    2022-07-29T05:56:02.607+00:00

    Hi @Dondon510 ,

    You can use the custom validation to build a conditional validation, refer the following sample:

    1. Create a UserProfile model: 225970-image.png
    2. Create a RequiredIfAttribute class: 226032-image.png
    3. MVC controller: 226061-image.png
    4. The View page: 225959-image.png Add the following scripts to achieve the custom client side validation: 225960-image.png

    You can view the above source code from here: 226071-customvalidation.txt

    Then, the output as below:

    226034-1.gif


    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,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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