简体   繁体   中英

ASP.NET MVC - validation rules not being created

My problem is the following:

I have a field where you insert a regex and I must check if it's valid regex or not (valid: [0-9], invalid: [). On my page I have some other fields with validation rules like [Required] or [StringLength] and they work client-side but this one does not.

Client-side validation javascript

function validateRegex() {
$.validator.addMethod("validateregex", function (value, element, params) {
    var isValid = true;
    if (value.length == 0) return true;

    try {
        var regex = new RegExp(value);
    } catch (e) {
        isValid = false;
    }

    console.log(isValid);
    return isValid;
});

$.validator.unobtrusive.adapters.add("validateregex", [], function (options) {
    options.rules["validateregex"] = true;
    options.messages["validateregex"] = options.message;
});

}

In ASP.NET MVC attribute I have this:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
        ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = "RegEx is not valid", // FormatErrorMessage(metadata.DisplayName),
            ValidationType = "validateregex"
        };

        rule.ValidationParameters.Add("errormessage", rule.ErrorMessage);
        yield return rule;
    }

and the IsValid method that returns ValidationResult, if regex is correct/incorrect.

<script type="text/javascript" src="~/Scripts/regexvalidator.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        validateRegex();


        //$("#saveSettings").on("click", function () {
        //    $("#optionForm").submit();
        //});
    });
</script>

Inside my .cshtml, in $(document).ready I call validateRegex function. Field in view is defined as:

<div class="form-group">
            @Html.LabelFor(m => m.Regex, new { @class = "control-label" })
            <div class="controls">
                @Html.TextBoxFor(p => p.Regex, new { @class = "form-control", id = "regexField" })
                @Html.ValidationMessageFor(p => p.Regex)
            </div>
        </div>

HTML view source:

<div class="controls">
                <input type="text" value="" name="Regex" id="regexField" class="form-control">
                <span data-valmsg-replace="true" data-valmsg-for="Regex" class="field-validation-valid"></span>
            </div>

All other validation rules work, except this.

Anyone know why?

Change:

<script type="text/javascript">
    function validateRegex() {
        $.validator.addMethod("validateregex", function (value, element, params) {
            var isValid = true;
            if (value.length == 0) return true;

            try {
                var regex = new RegExp(value);
            } catch (e) {
                isValid = false;
            }

            console.log(isValid);
            return isValid;
        });

        $.validator.unobtrusive.adapters.add("validateregex", [], function (options) {
            options.rules["validateregex"] = true;
            options.messages["validateregex"] = options.message;
        });
    }

    $(document).ready(function () {
        validateRegex();
    });
</script>

To:

<script type="text/javascript">
    $.validator.addMethod("validateregex", function (value, element, params) {
        var isValid = true;
        if (value.length == 0) return true;

        try {
            var regex = new RegExp(value);
        } catch (e) {
            isValid = false;
        }

        console.log(isValid);
        return isValid;
    });

    $.validator.unobtrusive.adapters.add("validateregex", [], function (options) {
        options.rules["validateregex"] = options.params;
        options.messages["validateregex"] = options.message;
    });
</script>

Putting the registration of the validators inside document.ready or window.load causes them to not register.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM