1

This is My Model:

public class PhoneNumber {

    public long Id { get; set; }
    public string Tel1 { get; set; }
    public string Tel2 { get; set; }
}

How can I force Clients in create action to fill at least One Tel (Tel1 or Tel2), I don't want to use any Clients Script, Or Controller Code, I just interested in use some attributes in above Model like [Required] to achieve this goal?

Saeid
  • 13,224
  • 32
  • 107
  • 173

3 Answers3

4

Just Change Model and use Custom Validator like this:

public class PhoneNumber : IValidatableObject {

    public long Id { get; set; }
    public string Tel1 { get; set; }
    public string Tel2 { get; set; }


public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
{

        var field1 = new[] { "Tel1" };
        var field2 = new[] { "Tel2" };

        if (string.IsNullOrEmpty(Tel1))
            if (String.IsNullOrEmpty(Tel2))
yield return new ValidationResult("At least Fill one of Tel1 or Tel2‏", field1);

        if (string.IsNullOrEmpty(Tel2))
        if (String.IsNullOrEmpty(Tel1))
yield return new ValidationResult("At least Fill one of Tel1 or Tel2", field2);
    }
}
2

This is similar to the following question which is answered here where it is suggested that you create a custom attribute.

Your model could then be written as:

[AtLeastOneRequired("Tel1", "Tel2", ErrorMessage="Please enter at least one value.")]
public class PhoneNumber { 

    public long Id { get; set; } 
    public string Tel1 { get; set; } 
    public string Tel2 { get; set; } 
} 

The description does describe writing javascript code to validate client side but this is optional if you only wanted to use server side validation.

Community
  • 1
  • 1
Dangerous
  • 4,818
  • 3
  • 33
  • 48
0

There is no baked-in validation attribute for that but it is easy to write your own. I don't know what you mean by no client side code but it is impossible to do this kind of client side validation without any client side code (not sure if HTML5 validations is supporting this kind of validation).

Here is a sample custom validation creation step by step blog post for you:

ASP.NET MVC: LessThan and GreaterThan Validation Attributes

larsen
  • 1,431
  • 2
  • 14
  • 26
tugberk
  • 57,477
  • 67
  • 243
  • 335