1. Create a RequiredIfAttribute class: public class RequiredIfAttribute : ValidationAttribute { private readonly string _comparisonProperty; public RequiredIfAttribute(string comparisonProperty) { _comparisonProperty = comparisonProperty; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ErrorMessage = ErrorMessageString; //get entered WorkPass Type var workpasstype = value == null ? "" : value.ToString(); var property = validationContext.ObjectType.GetProperty(_comparisonProperty); if (property == null) throw new ArgumentException("Property with this name not found"); //get the about value var workpasstypeValue = (string)property.GetValue(validationContext.ObjectInstance); if (workpasstype == "" && workpasstypeValue != null) return new ValidationResult(ErrorMessage); return ValidationResult.Success; } } 2. Create a BiodataViewModel model contains the relate properties: public class BiodataViewModel { //--WorkpassType ---// [Required(ErrorMessage = "Please Select WorkPass Type")] [Display(Name = "WorkPass Type"), StringLength(20)] public string WorkpassType { get; set; } //--Workpass Expiry Date ---// //[Required(ErrorMessage = "Please Select WorkPass Expiry Date")] [Display(Name = "WorkPass Expiry Date")] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [DataType(DataType.Date)] [RequiredIf("WorkpassType", ErrorMessage = "Please select WorkPass Expiry Date")] public DateTime? WorkpassExpiryDate { get; set; } } 3. Create a _BioData.cshtml page like this: @model Core3Razor.Data.BiodataViewModel
4. Create a CreateBioData page with page model the CreateBioData.cshtml @page @model Core3Razor.Pages.CreateBioDataModel
@section Scripts{ @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} } The CreateBioData.cshtml.cs public class CreateBioDataModel : PageModel { [BindProperty] public BiodataViewModel Biodata { get; set; } public void OnGet() { Biodata = new BiodataViewModel(); } public IActionResult OnPost() { //server side validation if (!ModelState.IsValid) { return Page(); } var WType = Biodata.WorkpassType; var WDate = Biodata.WorkpassExpiryDate; return RedirectToPage(nameof(Index)); } public void OnPostInsertBioData() { var newitem = Biodata; } }