Solved

ASP.Net MVC 4 C# -- conditional Model validation ?

Posted on 2013-06-12
2
3,166 Views
Last Modified: 2013-06-28
I have one app, but each car/truck has different
"WORK_ORDER" database table requirements.

How can I setup WORK_ORDER.cs conditional validation
since some controllers have different "REQUIRED fields" ?
--------------------------------------------------
WORK_ORDER.cs CURRENT
  ** [Required(ErrorMessage = "Supplier is required")]
     public string Supplier { get; set; }

WORK_ORDER.cs DESIRED
  ** if "car/truck" field is BUICK, then
     [Required(ErrorMessage = "Supplier is required")]
     public string Supplier { get; set; }
  ** else
     public string Supplier { get; set; }
--------------------------------------------------
Example
1. create a new \Controllers\BUICK_HeaderController.cs
2. system automatically creates \Views\BUICK_Header\Create.cshtml, Delete.cshtml, etc
3. repeat steps for OtherCars_DetailController.cs, OtherTrucks_DetailController.cs, etc
4. setup WORK_ORDER.cs conditional validation since
   some controllers have different "REQUIRED fields"
0
Comment
Question by:finance_teacher
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 16

Accepted Solution

by:
Stephan earned 500 total points
ID: 39243512
Hi, You probably need to create a new type of attributes that specifies your condition.

Here is version I mostly use:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class RequiredIfAttribute : ConditionalAttributeBase, IClientValidatable
    {
        private RequiredAttribute _innerAttribute = new RequiredAttribute();

        public string DependentProperty { get; set; }
        public object TargetValue { get; set; }

        public RequiredIfAttribute(string dependentProperty, object targetValue)
            : this(dependentProperty, targetValue, null)
        {
        }

        public RequiredIfAttribute(string dependentProperty, object targetValue, string errorMessage)
            : base(errorMessage)
        {
            this.DependentProperty = dependentProperty;
            this.TargetValue = targetValue;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (ShouldRunValidation(value, this.DependentProperty, this.TargetValue, validationContext))
            {
                if (!_innerAttribute.IsValid(value))
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
            }

            return ValidationResult.Success;
        }

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

            string depProp = BuildDependentPropertyId(metadata, context as ViewContext);

            string targetValue = (this.TargetValue ?? "").ToString();
            if (this.TargetValue != null && this.TargetValue.GetType() == typeof(bool))
                targetValue = targetValue.ToLower();

            rule.ValidationParameters.Add("dependentproperty", depProp);
            rule.ValidationParameters.Add("targetvalue", targetValue);

            yield return rule;
        }

        private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
        {
            return QualifyFieldId(metadata, this.DependentProperty, viewContext);
        }

        public override string FormatErrorMessage(string name)
        {
            if (!String.IsNullOrEmpty(this.ErrorMessageString))
                _innerAttribute.ErrorMessage = this.ErrorMessageString;
            return _innerAttribute.FormatErrorMessage(name);
        }
    }

Open in new window


It would be nice to add some client-side validation as well,
copy this code and place it after the unobstrusive validation script is loaded:
(function ($) {
    $.validator.addMethod('requiredif',
        function (value, element, parameters) {
            var id = '#' + parameters['dependentproperty'];
            var targetvalue = parameters['targetvalue'];
            targetvalue =
              (targetvalue == null ? '' : targetvalue).toString();
            var control = $(id);
            var controltype = control.attr('type');
            var actualvalue =
                controltype === 'checkbox' ?
                control.attr('checked').toString() :
                control.val();

            if (targetvalue === actualvalue)
                return $.validator.methods.required.call(
                  this, value, element, parameters);

            return true;
        }
    );

    $.validator.unobtrusive.adapters.add(
        'requiredif',
        ['dependentproperty', 'targetvalue'],
        function (options) {
            options.rules['requiredif'] = {
                dependentproperty: options.params['dependentproperty'],
                targetvalue: options.params['targetvalue']
            };
            options.messages['requiredif'] = options.message;
        }
    );
});

Open in new window


Then it is possible to use it like this:
[RequiredIf("TransportType", "BUICK", ErrorMessage = "Supplier is required")]
public string Supplier { get; set; }
0
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 39243529
Hi,

You can also use the IValidatableObject interface to provide model code validation.

Here is an example and more information IValidatableObject.


Regards,
Mishu
0

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question