3

I've been using a bootstrap modal to display a create form from a parent page. The forms works fine as it adds data to the database the way I want it to. It displays error messages for [Required] annotations and does not allow the form to save the data if there are any errors.

The problem lies in displaying the validation messages that my custom validation attribute contain. I also noticed that it is not triggering the IsValid function inside my own ValidationAttributes.

This is how my ValidationAttributes look like:

    public class FormulaSyntaxValidationAttribute : ValidationAttribute
{
    public FormulaSyntaxValidationAttribute()
        : base("The given formula is not formatted correctly.")
    { 

    }
    public override bool IsValid(object value)
    {
        return DbManager.ValidateStringIfValidFormula(value.ToString());
    }
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FormulaVariableValidationAttribute : ValidationAttribute
{
    public FormulaVariableValidationAttribute()
        : base("The given formula contains other variables instead of `g` or `G` (Gross Salary).")
    {

    }
    public override bool IsValid(object value)
    {
        return DbManager.ValidateFormulaVariables(value.ToString());
    }
}

While this is the model that uses the defined attribute:

    public partial class Formula
{
    public int FormulaId { get; set; }
    public int DeductionId { get; set; }

    [Required]
    [FormulaSyntaxValidation]
    [FormulaVariableValidation]
    [Display(Name = "Formula")]
    public string FormulaStatement { get; set; }

    [Required]
    [Display(Name = "Minimum Value")]
    public decimal MinimumValue { get; set; }

    [Required]
    [Display(Name = "Maximum Value")]
    public decimal MaximumValue { get; set; }

    public virtual Deduction Deduction { get; set; }
}

I use simple javascript that I also found in SO to show the validation messages. Here is what it looks like.

    (function ($) {
    $(document).ready(function () {
        $("#addFormulaModal").draggable({
            handle: ".modal-header"
        });

        $('#addFormulaModal').on('shown', function () {
            $('#addFormulaModal').removeData("validator");
            $('#addFormulaModal').removeData("unobtrusiveValidation");
            $.validator.unobtrusive.parse($("#formCreateFormula"));
        });

        $('#addFormulaModal').on('hidden', function () {
            location.reload(true);
        })


        $('#formCreateFormula').submit(function (event) {
            event.preventDefault();
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length == 0) {
                    $(this).removeClass('error');
                }
            });

            if (!$(this).valid()) {
                $(this).find('div.control-group').each(function () {
                    if ($(this).find('span.field-validation-error').length > 0) {
                        $(this).addClass('error');
                    }
                });
            }
        });

        $('#createFormSubmit').each(function () {
            $(this).find('div.control-group').each(function () {
                if ($(this).find('span.field-validation-error').length > 0) {
                    $(this).addClass('error');
                }
            });
        });

    });
})(jQuery);

var page = function () {

    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest(".control-group").addClass("error");
        },
        unhighlight: function (element) {
            $(element).closest(".control-group").removeClass("error");
        }
    });
}();

Thanks in Advance.

madth3
  • 7,275
  • 12
  • 50
  • 74
Andrei dela Cruz
  • 628
  • 4
  • 11
  • Possible duplicate of [How to give custom validation error messages for HTML validations?](https://stackoverflow.com/questions/53881655/how-to-give-custom-validation-error-messages-for-html-validations) – Googlian Jan 08 '19 at 19:43

0 Answers0