Vish
Vish

Reputation: 91

Set Required Field Validation based on condition in ASP.NET MVC

I want to Perform validation based on condition in ASP.NET MVC.

I have same page and model for Insert and update record, Now i want to set required field based on condition.

At time of insertion, EmployeeCode is Required, but at the time of Updation i don't want to set EmployeeCode is Required.

How can i perform validation like this case in asp.net mvc?

Upvotes: 0

Views: 4282

Answers (3)

Tsahi Asher
Tsahi Asher

Reputation: 1810

Use CustomeValidationAttribute.

First, decorate your property with [CustomValidationAttribute], specifying a validation method. E.g.

[CustomValidation(typeof(YourModel), nameof(ValidateEmployeeCode))]
public string EmployeeCode { get; set; }

ValidateEmployeeCode must by public, static, return ValidationResult, and accept an object as the first parameter, or the concrete type of the property being validated. It can also accept ValidationContext as the second parameter, which has useful properties such as the instance being validated and the display name of the property.

The method then checks based on the condition, if the value is empty or not, and return a ValidationResult.Success or a new ValidationResult with an error message, which is displayed to the user with the Html.ValidationMessageFor() call in the view. You can use the value of the record ID as a flag to know if it's a new record or an updated record.

Upvotes: 0

Manprit Singh Sahota
Manprit Singh Sahota

Reputation: 1339

You can use Fluent validation for the same.

RuleFor(x => x.EmployeeCode)
           .Must((o,e) =>
           {
               if (o.Id > 0)
               {
                   return true;
               }
               return !string.IsNullOrEmpty(o.EmployeeCode);
           })
           .WithMessage("Employee code is required");

You can also achieve this using Dataannotation validation. Let me know which library you are using along with version.

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

You can add custom validation logic by implementing IValidatableObject on the ViewModel.

public class MyViewModelThatMixesTwoUsecases : IValidatableObject {
    public string EmployeeCode { get; set; }
    public bool IsCreateUsecase { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (IsCreateUsecase && string.IsNullOrWhiteSpace(EmployeeCode)) {
            yield return new ValidationResult(
                "EmployeeCode is required for create usecase", 
                new[] {"EmployeeCode"}
            );
        }
    }
}

In the controller, test whether your model is valid by calling ModelState.IsValid.

Upvotes: 2

Related Questions