3

I have 2 text fields, text1 and text2, in my view model. I need to validate if text1 is entered then text2 must be entered and vice versa. How can this be achieved in the custom validation in the view model?

thanks.

Niner
  • 2,074
  • 6
  • 37
  • 47

4 Answers4

8

You can use implement IValidatableObject (from System.ComponentModel.DataAnnotations namespace) for the server side validation on your View Model:

public class AClass : IValidatableObject 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string SecondName { get; set; }
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if( (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(SecondName)) || (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(SecondName)) )
                yield return new ValidationResult("Name and Second Name should be either filled, or null",new[] {"Name","SecondName"});
        }
    }

Now it make sure if both Name and SecondName are set, or null, then model is valid, otherwise, it's not.

Amir
  • 9,577
  • 11
  • 41
  • 58
  • FYI, I recommend not returning the fields in the validation result when using a validation summary. If you return both the fields in the validation result, the validation summary will contain two messages instead of the expected single message. – Nicholas Westby Mar 31 '15 at 17:22
  • Can you include some code for how this would be used to annotate class properties too please? – niico Feb 24 '17 at 17:35
1

Look at mvc foolproof validation it does conditional validation. Find it on nuget or http://foolproof.codeplex.com

Edit The above is really old

I'd recommend MVC Fluent Validation for anything modern https://docs.fluentvalidation.net/en/latest/aspnet.html

GraemeMiller
  • 11,973
  • 8
  • 57
  • 111
0

If you'd like to use a data annotation validator and validation attributes on your model, you should take a look at this: " attribute dependent on another field"

Community
  • 1
  • 1
RickardN
  • 548
  • 4
  • 11
0

You can use JQuery, something like this:

$("input[x2]").hide();
    $("input[x1]").keypress(function() {
          var textValue = ("input[x1]").val();
         if(textValue) 
                      $("input[x2]").show();
        })
Amir978
  • 857
  • 3
  • 15
  • 38