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 7166667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T14:27:02+00:00 2026-05-28T14:27:02+00:00

I had two fields some thing like phone number and mobile number. Some thing

  • 0

I had two fields some thing like phone number and mobile number. Some thing like..

    [Required]
    public string Phone { get; set; }

    [Required]
    public string Mobile{ get; set; }

But user can enter data in either one of it. One is mandatory. How to handle them i.e how to disable the required field validator for one field when user enter data in another field and viceversa. In which event i have to handle it in javascript and what are the scripts i need to add for this. Can anyone please help to find the solution…

  • 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-28T14:27:03+00:00Added an answer on May 28, 2026 at 2:27 pm

    One possibility is to write a custom validation attribute:

    public class RequiredIfOtherFieldIsNullAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string _otherProperty;
        public RequiredIfOtherFieldIsNullAttribute(string otherProperty)
        {
            _otherProperty = otherProperty;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(_otherProperty);
            if (property == null)
            {
                return new ValidationResult(string.Format(
                    CultureInfo.CurrentCulture, 
                    "Unknown property {0}", 
                    new[] { _otherProperty }
                ));
            }
            var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
    
            if (otherPropertyValue == null || otherPropertyValue as string == string.Empty)
            {
                if (value == null || value as string == string.Empty)
                {
                    return new ValidationResult(string.Format(
                        CultureInfo.CurrentCulture,
                        FormatErrorMessage(validationContext.DisplayName),
                        new[] { _otherProperty }
                    ));
                }
            }
    
            return null;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "requiredif",
            };
            rule.ValidationParameters.Add("other", _otherProperty);
            yield return rule;
        }
    }
    

    which you would apply to one of the properties of your view model:

    public class MyViewModel
    {
        [RequiredIfOtherFieldIsNull("Mobile")]
        public string Phone { get; set; }
    
        public string Mobile { get; set; }
    }
    

    then you could have a controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    and finally a view in which you will register an adapter to wire the client side validation for this custom rule:

    @model MyViewModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery.validator.unobtrusive.adapters.add(
            'requiredif', ['other'], function (options) {
    
                var getModelPrefix = function (fieldName) {
                    return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
                }
    
                var appendModelPrefix = function (value, prefix) {
                    if (value.indexOf('*.') === 0) {
                        value = value.replace('*.', prefix);
                    }
                    return value;
                }
    
                var prefix = getModelPrefix(options.element.name),
                    other = options.params.other,
                    fullOtherName = appendModelPrefix(other, prefix),
                    element = $(options.form).find(':input[name="' + fullOtherName + '"]')[0];
    
                options.rules['requiredif'] = element;
                if (options.message) {
                    options.messages['requiredif'] = options.message;
                }
            }
        );
    
        jQuery.validator.addMethod('requiredif', function (value, element, params) {
            var otherValue = $(params).val();
            if (otherValue != null && otherValue != '') {
                return true;
            }
            return value != null && value != '';
        }, '');
    </script>
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Phone)
            @Html.EditorFor(x => x.Phone)
            @Html.ValidationMessageFor(x => x.Phone)
        </div>
    
        <div>
            @Html.LabelFor(x => x.Mobile)
            @Html.EditorFor(x => x.Mobile)
            @Html.ValidationMessageFor(x => x.Mobile)
        </div>
    
        <button type="submit">OK</button>
    }
    

    Pretty sick stuff for something so extremely easy as validation rule that we encounter in our everyday lives. I don’t know what the designers of ASP.NET MVC have been thinking when they decided to pick a declarative approach for validation instead of imperative.

    Anyway, that’s why I use FluentValidation.NET instead of data annotations to perform validations on my models. Implementing such simple validation scenarios is implemented in a way that it should be – simple.

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

Sidebar

Related Questions

If you had two snippets: (global-set-key \C-d delete-char) and (define-key global-map \C-d delete-char) Is
I'm trying to generate a data set, and I think recursion is required, but
If, for example, I had two fields such as 'Dog' and 'Cat' that defines
I had a previous question combining two questions on this subject...but I think I
A number of times over the last month I've had to replace 'null' fields
I had two separate interfaces, one 'MultiLingual' for choosing language of text to return,
Originally I had two tables in my DB, [Property] and [Employee]. Each employee can
That is, if I had two or more sets, and I wanted to return
So I just started my first rails project yesterday. I had two many-to-many (has_and_belongs_to_many)
This is a link to a question I had asked two days back, How

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.