Razor Model Validation
From Logic Wiki
Model Validation Annotation
Including Combined validations by using IValidatableObject
public class RenewPracticeDetails : IValidatableObject
{
public string LegalName { get; set; }
[Required(ErrorMessage = "The Name of the Practice as it appears on your bank statement field is required.")]
public string LegalNameOnStatement { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var controlName = new List<string>();
if (TradingStatus == 3 && string.IsNullOrEmpty(LPNumber))
{
controlName.Add("LPNumber");
yield return new ValidationResult("You must supply a LP Number", controlName);
}
if (TradingStatus == 4 && string.IsNullOrEmpty(LLPNumber))
{
controlName.Add("LLPNumber");
yield return new ValidationResult("You must supply a LLP Number", controlName);
}
}
}
in CSHTML
@Html.TextBoxFor(m=> m.LegalNameOnStatement, "", new { @class = "form-control" })
@Html.ValidationMessage("LegalNameOnStatement")
<div class="radio" id="div_4" >
<fieldset>
<label class="control-label radioLabel" for="llpNumber">LLP Number</label>
@Html.TextBoxFor(m => m.LLPNumber, "", new { @class = "form-control" })
@Html.ValidationMessage("LLPNumber")
</fieldset>
</div>
Controller
[HttpPost]
public async Task<IActionResult> PracticeDetails(RenewPracticeDetails renewPracticeDetails)
{
if (ModelState.IsValid)
{
....
}
return View(renewPracticeDetails);
}