1

Is there a method to implement a required attribute to my virtualPassword property, but with the condition if Password in null?

Here’s my code.

[DataType(DataType.Password)]
[LocalizedDisplayName("UserPassword", NameResourceType = typeof(Languages.Names))]
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Languages.Validations))]        
public string Password { get; set; }

private string _virtualPassword = null;
[NotMapped]
[DataType(DataType.Password)]
[LocalizedDisplayName("UserPassword", NameResourceType = typeof(Languages.Names))]
[StringLength(12, MinimumLength = 6, ErrorMessageResourceName = "StringLengthBetween", ErrorMessageResourceType = typeof(Languages.Validations))]
public virtual string virtualPassword { get { return _virtualPassword; } set { _virtualPassword = value; } }
memeonline
  • 115
  • 2
  • 6
  • I've used the following from another answer. http://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute – Kyle C Jan 31 '13 at 17:50

1 Answers1

0

You could implement a custom validation by implementing IValidatableObject in your model.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var issues = new List<ValidationResult>();
if(issue_exist_in_model) //implement whatever condition is applicable
{
    issues.Add(new ValidationResult("Message for issur that exist"));
}

  return issues;
}
scartag
  • 17,548
  • 3
  • 48
  • 52
  • I really don't understand why people constantly suggest this without also telling them that this does not work with client-side validation. It can create weird situations where validation fails, you fix it, it posts, then validation fails again with a different set of validation errors. These days, client-side validation is used by almost everyone. – Erik Funkenbusch Jan 31 '13 at 17:54
  • @MystereMan i guess you are right, but he wanted to know about custom validation. At least he knows it exists. Maybe i should append some words of advice to my answer :) – scartag Jan 31 '13 at 17:55