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.
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.
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.
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
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"
You can use JQuery, something like this:
$("input[x2]").hide();
$("input[x1]").keypress(function() {
var textValue = ("input[x1]").val();
if(textValue)
$("input[x2]").show();
})