MVC 2 validation attributes - validation of one of two values

Can anyone help me on this. I am trying to figure out how to check two values ​​in a form, I need to fill out one of the two elements. How to make sure that one or both elements are entered?

I am using viewmodels in ASP.NET MVC 2.

Here is a small piece of code:

View:

Email: <%=Html.TextBoxFor(x => x.Email)%>
Telephone: <%=Html.TextBoxFor(x => x.TelephoneNumber)%>

View Model:

    [Email(ErrorMessage = "Please Enter a Valid Email Address")]
    public string Email { get; set; }

    [DisplayName("Telephone Number")]
    public string TelephoneNumber { get; set; }

I want to provide any of these details.

Thanks for any pointers.

+3
source share
1 answer

Perhaps you can do this in the same way as the attribute PropertiesMustMatchthat is included with the File-> New-> ASP.NET MVC 2 web application.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class EitherOrAttribute : ValidationAttribute
{
    private const string _defaultErrorMessage = "Either '{0}' or '{1}' must have a value.";
    private readonly object _typeId = new object();

    public EitherOrAttribute(string primaryProperty, string secondaryProperty)
        : base(_defaultErrorMessage)
    {
        PrimaryProperty = primaryProperty;
        SecondaryProperty = secondaryProperty;
    }

    public string PrimaryProperty { get; private set; }
    public string SecondaryProperty { get; private set; }

    public override object TypeId
    {
        get
        {
            return _typeId;
        }
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
            PrimaryProperty, SecondaryProperty);
    }

    public override bool IsValid(object value)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        object primaryValue = properties.Find(PrimaryProperty, true /* ignoreCase */).GetValue(value);
        object secondaryValue = properties.Find(SecondaryProperty, true /* ignoreCase */).GetValue(value);
        return primaryValue != null || secondaryValue != null;
    }
}

IsValid, , .

, :

[EitherOr("Email", "TelephoneNumber")]
public class ExampleViewModel
{
    [Email(ErrorMessage = "Please Enter a Valid Email Address")]
    public string Email { get; set; }

    [DisplayName("Telephone Number")]
    public string TelephoneNumber { get; set; }
}

, , (, , ), , , .

+5

Source: https://habr.com/ru/post/1755709/


All Articles