Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1067079
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T20:06:20+00:00 2026-05-16T20:06:20+00:00

I am trying to validate that either of 2 textbox fields in my view

  • 0

I am trying to validate that either of 2 textbox fields in my view have a value supplied. I made this Model Validator:

public class RequireEitherValidator : ModelValidator
{
    private readonly string compareProperty;
    private readonly string errorMessage;

    public RequireEitherValidator(ModelMetadata metadata,
    ControllerContext context, string compareProperty, string errorMessage)
        : base(metadata, context)
    {
        this.compareProperty = compareProperty;
        this.errorMessage = errorMessage;
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        if (Metadata.Model == null)
            yield break;
        var propertyInfo = container.GetType().GetProperty(compareProperty);
        if (propertyInfo == null)
            throw new InvalidOperationException("Unknown property:" + compareProperty);

        string valueToCompare = propertyInfo.GetValue(container, null).ToString();

        if (string.IsNullOrEmpty(Metadata.Model.ToString()) && string.IsNullOrEmpty(valueToCompare))
            yield return new ModelValidationResult
            {
                Message = errorMessage
            };
    }
}

This validation logic never gets hit and I think it’s because no value gets supplied to the textboxes.

In case you need it, here’s the provider and attribute I created along with the attribute usage:

public class MyValidatorProvider : AssociatedValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(
        ModelMetadata metadata, ControllerContext context,
        IEnumerable<Attribute> attributes)
    {
        foreach (var attrib in attributes.OfType<RequireEitherAttribute>())
            yield return new RequireEitherValidator(metadata, context,
            attrib.CompareProperty, attrib.ErrorMessage);
    }
}

public class RequireEitherAttribute : Attribute
{
    public readonly string CompareProperty;
    public string ErrorMessage { get; set; }

    public RequireEitherAttribute(string compareProperty)
    {
        CompareProperty = compareProperty;
    }
}

public class StudentLogin
{
    [DisplayName("Last Name")]
    [Required(ErrorMessage = "You must supply your last name.")]        
    public string LastName { get; set; }

    [DisplayName("Student ID")]
    [RegularExpression(@"^\d{1,8}$", ErrorMessage = "Invalid Student ID")]
    [RequireEither("SSN", ErrorMessage = "You must supply your student id or social security number.")]        
    public int? StudentId { get; set; }

    [DisplayName("Social Security Number")]
    [RegularExpression(@"^\d{9}|\d{3}-\d{2}-\d{4}$", ErrorMessage = "Invalid Social Security Number")]
    public string SSN { get; set; }
}

My view:

 <%Html.BeginForm(); %>
    <p>
        Please supply the following information to login:</p>
    <ol class="standard">
        <li>
            <p>
                <%=Html.LabelFor(x => x.LastName) %><br />
                <%=Html.TextBoxFor(x => x.LastName)%>
                <%=Html.ValidationMessageFor(x => x.LastName) %></p>
        </li>
        <li>
            <p>
                <%=Html.LabelFor(x => x.StudentId) %><br />
                <%=Html.TextBoxFor(x => x.StudentId) %>
                <%=Html.ValidationMessageFor(x => x.StudentId) %></p>
            <p style="margin-left: 4em;">
                - OR -</p>
            <p>
                <%=Html.LabelFor(x => x.SSN)%><br />
                <%=Html.TextBoxFor(x => x.SSN) %>
                <%=Html.ValidationMessageFor(x => x.SSN) %>
            </p>
        </li>
    </ol>
    <%=Html.SubmitButton("submit", "Login") %>
    <%Html.EndForm(); %>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T20:06:22+00:00Added an answer on May 16, 2026 at 8:06 pm

    One way to approach this is not just create a ValidationAttribute and apply this at the class level.

    [RequireEither("StudentId", "SSN")]
    public class StudentLogin
    

    The error message will automatically show up in the Validation Summary. The attribute would look something like this (I’ve drastically simplified the validation logic inside IsValid() by treating everything as strings just for brevity:

    public class RequireEither : ValidationAttribute
    {
        private string firstProperty;
        private string secondProperty;
    
        public RequireEither(string firstProperty, string secondProperty)
        {
            this.firstProperty = firstProperty;
            this.secondProperty = secondProperty;
        }
    
        public override bool IsValid(object value)
        {
            var firstValue = value.GetType().GetProperty(this.firstProperty).GetValue(value, null) as string;
            var secondValue = value.GetType().GetProperty(this.secondProperty).GetValue(value, null) as string;
    
            if (!string.IsNullOrWhiteSpace(firstValue))
            {
                return true;
            }
    
            if (!string.IsNullOrWhiteSpace(secondValue))
            {
                return true;
            }
            // neither was supplied so it's not valid
            return false;
        }
    }
    

    Note that in this case the object passed to IsValid() is the instance of the class itself rather than the property.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an XML file that I'm trying to validate against an XSD file
I'm trying to validate that a submitted URL doesn't already exist in the database.
I was trying to validate an XML signature. The validation according to this tutorial
I have the following view models: public class Search { public int Id {
I've been trying to validate an inputted string ( sys argv[1] in this case).
I am trying to validate that the given string contains contains only letters, numbers,
I have a function that expects real numbers (either integers or floats) as its
I'm trying to create a simple form that will validate that the first password
I am trying to validate one block of json data that I receive from
I'm trying to validate that a parameter is both an out parameter and extends

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.