Niner
Niner

Reputation: 2205

asp.net mvc validation on 2 fields - one must exist if other entered

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.

Upvotes: 3

Views: 6549

Answers (4)

GraemeMiller
GraemeMiller

Reputation: 12253

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

Upvotes: 1

RickardN
RickardN

Reputation: 548

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"

Upvotes: 0

Amir
Amir

Reputation: 9627

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.

Upvotes: 8

Amir978
Amir978

Reputation: 923

You can use JQuery, something like this:

$("input[x2]").hide();
    $("input[x1]").keypress(function() {
          var textValue = ("input[x1]").val();
         if(textValue) 
                      $("input[x2]").show();
        })

Upvotes: 0

Related Questions