Hi @net 6 newbie ,
I want the following sequence of validation
Required ->CustomAttribute1->CustomAttribute2
You can create one custom validation attribute which contains three validation rules.
For example:
public class Model1
{
[CustomAttribute]
public string data1 {get; set;}
}
In the custom attribute, you can add validation rules, and if you want to display error messages one by one, you can return validation results in the "if" statement. If you want to display all error messages at once, you can define a variable to collect the error messages and then return the error messages after the validation rule is complete.
public class CustomAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//get the entered value
var model= (Model1)validationContext.ObjectInstance;
//define a variable to collect the error message, after that display them at once.
//var errormessage ="";
//Check if the data is null or empty
if (String.IsNullOrEmpty(model.data1))
{
//if data is null.
return new ValidationResult(ErrorMessage == null ? "Value is required" : ErrorMessage);
}
//CustomAttribute1 validation rules
//if(condition){}
//CustomAttribute2 validation rules
//if(condition){}
//If you want to display all the validation message at once, use an `if` statement to check whether the errormessage is null, then return the validation result.
return ValidationResult.Success;
}
}
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