1. UserProfile.cs: using MVCWebApplication.CustomValidation; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MVCWebApplication.Models { public class UserProfile { public int UserID { get; set; } [Required] public string Name { get; set; } [NotMapped] public bool IsChangePassword { get; set; } [DataType(DataType.Password)] [Display(Name = "New Password")] [RequiredIf("IsChangePassword")] [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; } } } 2. RequiredIfAttribute.cs: using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using System.ComponentModel.DataAnnotations; namespace MVCWebApplication.CustomValidation { [AttributeUsage(AttributeTargets.Property)] public class RequiredIfAttribute : ValidationAttribute, IClientModelValidator { private string PropertyName { get; set; } public RequiredIfAttribute(string propertyName) { PropertyName = propertyName; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { //get the userprofile instance object instance = validationContext.ObjectInstance; Type type = instance.GetType(); //get the property value based on the property name. Here we can get the IsChangePassword value. bool.TryParse(type.GetProperty(PropertyName).GetValue(instance)?.ToString(), out bool propertyValue); //check whether the IsChangePassword checkbox is checked, if yes, validate the password. if not, ignore the password validation. if (propertyValue && string.IsNullOrWhiteSpace(value?.ToString())) { return new ValidationResult(ErrorMessage); } return ValidationResult.Success; } public void AddValidation(ClientModelValidationContext context) { MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, "data-val-requiredif", "Since checked the ChangePasswork, please enter tne new password"); } public static bool MergeAttribute(IDictionary attributes, string key, string value) { if (attributes.ContainsKey(key)) { return false; } attributes.Add(key, value); return true; } } } 3. Controller: public IActionResult EditUser() { var user = new UserProfile() { UserID = 101, Name = "Tom", IsChangePassword = false, }; return View(user); } [HttpPost] public IActionResult EditUser(UserProfile user) { if (ModelState.IsValid) { //update user return View(nameof(Index)); } return View(user); } 4. EditUser.cshtml page: @model MVCWebApplication.Models.UserProfile
@section Scripts{ @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }