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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T18:59:57+00:00 2026-06-14T18:59:57+00:00

I am using Asp.net MVC3, razor view engine and data annotation for model validation.

  • 0

I am using Asp.net MVC3, razor view engine and data annotation for model validation.

I have a form in which have to input Url details(Url and Description).Both fields are not required. But if i input one field other must be required.If i input description Url is required and is in correct format and if i enter Url then description is required.

I created a customvalidator for data annotation .It validates and output error message.
But my problem is error message generated by ValidationMessageFor is in incorrect place.
ie,if i enter description ,the required url message, is part of description.
I expect that message as part of ValidationMessageFor url field.

Can any one can help me? Thanks in advance. Folowing are the code i used

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]

public sealed class IsExistAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} is required."; 
public string OtherProperty { get; private set; } 
public IsExistAttribute (string otherProperty)
    : base(DefaultErrorMessage)
{
    if (string.IsNullOrEmpty(otherProperty))
    {
        throw new ArgumentNullException("otherProperty");
    }

    OtherProperty = otherProperty;
}

public override string FormatErrorMessage(string name)
{
    return string.Format(ErrorMessageString, name, OtherProperty);
}

protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
    if (value != null)
    {
        var otherProperty = validationContext.ObjectInstance.GetType()
                                             .GetProperty(OtherProperty);

        var otherPropertyValue = otherProperty
                                    .GetValue(validationContext.ObjectInstance, null);
        var strvalue=Convert.ToString(otherPropertyValue)

        if (string.IsNullOrEmpty(strvalue))
        {
            //return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));

            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName),new[] { OtherProperty});

        }
    }

    return ValidationResult.Success;
 } 

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context)
{
    var clientValidationRule = new ModelClientValidationRule()
    {
       ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
       ValidationType = "isexist"
    };

   clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty); 
   return new[] { clientValidationRule };           
}      
}

in model

[Display(Name = "Description")]
[IsExist("Url")]
public string Description { get; set; }

[Display(Name = "Url")]
[IsExist("Description")]
[RegularExpression("(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?", ErrorMessage  = "Invalid Url")]
public string Url { get; set; }

and in view

<div class="editor-field">
@Html.TextBoxFor(m => m.Description )
@Html.ValidationMessageFor(m => m.Description)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Url)
@Html.ValidationMessageFor(m => m.Url)
</div>

unobstrusive validation logic

(function ($) {
    $.validator.addMethod("isexist", function (value, element, params) {
        if (!this.optional(element)) {
            var otherProp = $('#' + params)
            return (otherProp.val() !='' &&  value!='');//validation logic--edited by Rajesh 
        }
        return true;
    });
    $.validator.unobtrusive.adapters.addSingleVal("isexist", "otherproperty");                        
} (jQuery));  
  • 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-06-14T18:59:58+00:00Added an answer on June 14, 2026 at 6:59 pm

    You should make the validation the other way round. Change:

    if (string.IsNullOrEmpty(otherPropertyValue))
        {
            //return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName),new[] { OtherProperty});
    
        }
    

    To:

    if (string.IsNullOrEmpty(Convert.ToString(value)) && !string.IsNullOrEmpty(otherPropertyValue))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    

    And remove if (value != null)

    The field that will then get invalidated is the empty one, in the case the other one is filled.

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

Sidebar

Related Questions

I am using ASP.NET MVC 3 with the Razor view engine . I have
I'm developing an ASP.NET MVC3 application using the new Razor view engine but I'm
I am using ASP.NET MVC 3 with the razor view engine. I have the
We're using ASP.NET MVC3 with Razor View engine and standard HTML and jquery on
I am using ASP.NET MVC3 with the razor view engine. I am also using
I am using ASP.Net MVC 3 Razor view engine. I have a requirement to
I am using Razor syntax in an ASP.NET MVC3 View inside a JavaScript code
I'm developing a dashboard using ASP.NET MVC3 and need to have two divs which
In ASP.NET MVC3, when a view model is passed into a view using return
Is there any documentation on how to use the Razor view engine using ASP.NET

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.