Hello @Kuler Master ,
Thanks for sharing your code! Here’s how you can make the Company Name validation conditional in a way that’s clean and works well with Blazor.
About your codes:
- You’re putting validation logic inside your model class by inheriting from
ValidationAttribute. - This isn’t the right way, your model should just be a data container, and validation attributes should be separate.
- The
[Required]attribute onCompanyNamemakes it always required, which isn’t what you want.
How to Fix It :
- Remove the
[Required]fromCompanyName. - Create a custom validation attribute (like
RequiredIf) that only requiresCompanyNameifAccountTypeis "company". - Apply that attribute to
CompanyName.
#Here’s How You Do It:
1. Custom Attribute
public class RequiredIfCompanyAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var cred = (Credential)validationContext.ObjectInstance;
// Let's say AccountType == 1 means "Company"
if (cred.AccountType == 1 && string.IsNullOrWhiteSpace(value as string))
{
return new ValidationResult("Company Name is required when Account Type is Company.");
}
return ValidationResult.Success;
}
}
2. Update Your Model
public class Credential
{
[Required(ErrorMessageResourceName = "Validation_RequiredField", ErrorMessageResourceType = typeof(Resources))]
public int? AccountType { get; set; }
[Required(ErrorMessageResourceName = "Validation_RequiredField", ErrorMessageResourceType = typeof(Resources))]
public string? FirstName { get; set; }
[Required(ErrorMessageResourceName = "Validation_RequiredField", ErrorMessageResourceType = typeof(Resources))]
public string? LastName { get; set; }
[RequiredIfCompany]
public string? CompanyName { get; set; }
}
3. Your Blazor Form
Your form markup is fine! The validation will now work as you want:
- If "Company" is selected, "Company Name" must be filled in.
- If "Private" is selected, "Company Name" can be left blank.
Hope this helps!