1

I have scenario where i need to apply either one(Email or Phone) has required field. Both Can not be null or Empty.

This is my Class.

 public class Contact 
 {
    public Email Email {get; set;}
    public Phone Phone {get; set;}
 }


public class Email
{
 [Required]
 public string EmailAddress {get;set;}
}

public class Phone 
{
[Required]
public int CountryCode {get; set;}

[Required]
public string Number {get; set;}
}
avi jain
  • 33
  • 3
  • Have you heard of Fluent validations? You can make validation rules that apply to multiple fields. https://fluentvalidation.net – Jeremy Thompson Jul 02 '18 at 08:51
  • 1
    Possible duplicate of https://stackoverflow.com/questions/20152757/ef-require-either-of-two-fields and https://stackoverflow.com/questions/20152757/ef-require-either-of-two-fields – OL. Jul 02 '18 at 08:51
  • Possible duplicate of [EF - Require either of two fields?](https://stackoverflow.com/questions/20152757/ef-require-either-of-two-fields) – Jinto Jacob Jul 02 '18 at 08:53
  • See this example of how it's done with FirstName and Surname "either or" must not be empty: https://stackoverflow.com/a/21115780/495455 – Jeremy Thompson Jul 02 '18 at 08:55
  • Thank you so much each and everyone. Can it be done via model validation with out fluent validation. Probably EF - Require either of two fields? will work out i guess. I will check once. – avi jain Jul 02 '18 at 09:04
  • This one also is related https://stackoverflow.com/questions/9560227/either-or-required-validation?noredirect=1&lq=1 – OL. Jul 02 '18 at 09:04

1 Answers1

0

One of the best methods I would suggest for solving this would be to use a Remote attribute, which will allow you to validate your value against a specific method to determine validity :

Remove Validation Attributes

[Remote("IsPhoneOrEmail", "YourController", ErrorMessage = "Not a valid phone or e-mail!")]
public string Notification { get; set;}

which calls a specific method to perform your validation :

public ActionResult IsPhoneOrEmail(string notification) 
{
     Regex phoneRegex = new Regex(@"^([0-9\(\)\/\+ \-]*)$");
     Regex emailRegex = new Regex("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");

     return (emailRegex .IsMatch(notification) || phoneRegex.IsMatch(notification));
}
Jinto Jacob
  • 385
  • 2
  • 17
jay vyas
  • 11
  • 3