0

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?

4
  • Do you use different controller? Commented Aug 23, 2017 at 7:36
  • 1
    Use different view models, or you need a conditional validation attribute (e.g. a foolproof [RequiredIf] attribute) Commented Aug 23, 2017 at 7:37
  • I am use same controller Commented Aug 23, 2017 at 7:44
  • I don't know about how to use RequiredIf. Can you please help me Commented Aug 23, 2017 at 7:45

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

I am using DataAnnotation Validation
0

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.

2 Comments

Can you give me demo for that?
@Vish, I've already showed how to decorate the validated property. The validation method looks like this: public static ValidationResult ValidateEmployeeCode(string value, ValidationContext context) { ValidationResult result = ValidationResult.Success; if (value <> [valid value]) { result = new ValidationResult("Employee Code is not valid."); } return result; } any value other than ValidationResult.Success (which is actually null) will trigger a validation error in the validation mechanism of MVC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.