0

i have an object which contains Max value and Min value,, so i want inside all the edit and create views to display a client side validation message incase the user insert the Min value greater then the Min value. BR

John John
  • 1
  • 72
  • 238
  • 501
  • Do you mean a Range validation ? – fmgp May 02 '12 at 20:43
  • Thanks for the reply , no i do not mean range . What i am trying to do is that i have an object named LabResult where each LabResult object have two properties that the doctor should enter; Test_Min_Value & Test_Max_Value. So to avoid illogical numbers i want to check that the entered Test_Max_Value should be greater than Test_Min_Value. BR – John John May 02 '12 at 22:01
  • 2
    Check out http://stackoverflow.com/questions/4784943/asp-net-mvc-3-client-side-validation-with-parameters/4784986#4784986 and http://stackoverflow.com/questions/5920403/asp-net-mvc-3-data-annotations-greaterthan-lowerthan-for-datetime-and-int – DMulligan May 03 '12 at 00:38

1 Answers1

1

You will probably want both client-side and server-side validation. It might be good to implement your own Validation. I did a similar thing in which I wanted to make sure that one field was NOT the same value as another field. I didn't start from scratch though. I used some code from Simon J Ince of Microsoft. He has it here on his blog. Basically he has a foundation of Conditional Validation (where you validate based on the value of another field). I inherited from his ConditionalAttributeBase and implemented the IClientValidatable interface (this is how you send to the browser the dependent field the java script will check with.)

/// <summary>
/// A validator for ensuring that the value of this field does NOT equal the value of another field.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class NotEqual:ConditionalAttributeBase, IClientValidatable
{
    public string DependentProperty { get; set; }

    /// <summary>
    /// Returns client validation rules for NotEqual
    /// </summary>
    /// <param name="metadata">The model metadata.</param>
    /// <param name="context">The controller context.</param>
    /// <returns>
    /// The client validation rules for NotEqual.
    /// </returns>
    IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
                       {
                           ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                           ValidationType = "notequal",
                       };
        string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
        rule.ValidationParameters.Add("dependentproperty", depProp);

        yield return rule;
    }

    /// <summary>
    /// Builds the dependent property id.
    /// </summary>
    /// <param name="metadata">The metadata.</param>
    /// <param name="viewContext">The view context.</param>
    /// <returns></returns>
    protected string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
    {
        return QualifyFieldId(metadata, DependentProperty, viewContext);
    }

    /// <summary>
    /// Validates that the value does not equal the value of the dependent value if the dependent value is not null
    /// </summary>
    /// <param name="value">The value to validate.</param>
    /// <param name="validationContext">The context information about the validation operation.</param>
    /// <returns>
    /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> class.
    /// </returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // check if the current value matches the target value
        if (value != null && GetDependentFieldValue(DependentProperty, validationContext).ToString() == value.ToString())
        {

                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="NotEqual"/> class.
    /// </summary>
    /// <param name="dependentProperty">The dependent property.</param>
    public NotEqual(string dependentProperty)
    {
        DependentProperty = dependentProperty;
    }

}$

Next I tweaked the javascript:

    (function ($) {
        $.validator.addMethod('notequal',
            function (value, element, parameters) {
                var id = '#' + parameters['dependentproperty'];
                var depControl = $(id);
                var control = $(element);
                if (control.val() === depControl.val())
                    return "";
                return true;
            }
        );

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

        $.validator.addMethod('notequaltwo',
        function (value, element, parameters) {
            var id = '#' + parameters['dependentproperty'];
            var depControl = $(id);
            var control = $(element);
            if (control.val() === depControl.val())
                return "";
            return true;
        }
    );

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

Hopefully you can see how you can adapt my code to do what you want it do, basically you would have to convert the types (if the types don't convert, don't do anything and other validators that you have should pick up on it.) and then do a compare.

jMo
  • 101
  • 3