简体   繁体   中英

How can I compare the key to a string in a JQuery $.each loop?

I'm trying to get the error message out of a custom data attribute JQuery unobtrusive adapter, but I can't seem to extract the error message into a variable. My validation message just returns as:

Warning: No message defined for Image

The code is as follows:

$(document).ready(function () {
var errorMessage;
$.validator.unobtrusive.adapters.add(
    'filesize', ['maxsize'], function (options) {
        options.rules['filesize'] = options.params;

        if (options.message) {
            options.message['filesize'] = options.message;             

            $.each(options, function (key, val) {
                console.log("Key: " + key + " | Value: " + val);
                if (key === "message") {
                    errorMessage = val;
                }
            });

        }
    });

$.validator.addMethod('filesize', function (value, element, params) {
    if (element.files.length < 1) {
        // No files selected
        return true;
    }

    if (!element.files || !element.files[0].size) {
        // This browser doesn't support the HTML5 API
        return true;
    }

    return element.files[0].size < params.maxsize;
}, errorMessage); // This is where the variable errorMessage is used
});

Also, when I use the correct JQuery syntax of options.messages (plural) and leave out the whole $.each block, my Firefox crashes when I open Firebug?

You'd normally specify the error message at the custom validation attribute that you wrote on your view model:

public class MyViewModel
{
    [Required]
    [MaxFileSize(8388608, ErrorMessage = "Maximum allowed file size is {0} bytes")]
    public HttpPostedFileBase File { get; set; }
}

and then have a custom validation attribute:

public class MaxFileSizeAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int _maxFileSize;
    public MaxFileSizeAttribute(int maxFileSize)
    {
        _maxFileSize = maxFileSize;
    }

    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;
        if (file == null)
        {
            return false;
        }
        return file.ContentLength <= _maxFileSize;
    }

    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(_maxFileSize.ToString());
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(_maxFileSize.ToString()),
            ValidationType = "filesize"
        };
        rule.ValidationParameters["maxsize"] = _maxFileSize;
        yield return rule;
    }
}

and the unobtrusive adapter:

jQuery.validator.unobtrusive.adapters.add(
    'filesize', [ 'maxsize' ], function (options) {
        options.rules['filesize'] = options.params;
        if (options.message) {
            options.messages['filesize'] = options.message;
        }
    }
);

jQuery.validator.addMethod('filesize', function (value, element, params) {
    if (element.files.length < 1) {
        // No files selected
        return true;
    }

    if (!element.files || !element.files[0].size) {
        // This browser doesn't support the HTML5 API
        return true;
    }

    return element.files[0].size < params.maxsize;
}, '');

To compare a key to a string with $.each you can simply do

var myObj = {'message1' : 1, 'message2' : 2};
$.each(​myObj, function(key){
     if(key == 'message1'){
         alert('they match!');                     
     }                                
});​

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