yii.validation.js 12.4 KB
Newer Older
Qiang Xue committed
1
/**
Qiang Xue committed
2
 * Yii validation module.
Qiang Xue committed
3
 *
Qiang Xue committed
4
 * This JavaScript module provides the validation methods for the built-in validators.
Qiang Xue committed
5 6 7 8 9 10 11 12
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */

Qiang Xue committed
13
yii.validation = (function ($) {
Qiang Xue committed
14 15 16 17 18 19
    var pub = {
        isEmpty: function (value) {
            return value === null || value === undefined || value == [] || value === '';
        },

        addMessage: function (messages, message, value) {
20
            messages.push(message.replace(/\{value\}/g, value));
Qiang Xue committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        },

        required: function (value, messages, options) {
            var valid = false;
            if (options.requiredValue === undefined) {
                var isString = typeof value == 'string' || value instanceof String;
                if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? $.trim(value) : value)) {
                    valid = true;
                }
            } else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) {
                valid = true;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        boolean: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }
            var valid = !options.strict && (value == options.trueValue || value == options.falseValue)
                || options.strict && (value === options.trueValue || value === options.falseValue);

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        string: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value !== 'string') {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value.length < options.min) {
                pub.addMessage(messages, options.tooShort, value);
            }
            if (options.max !== undefined && value.length > options.max) {
                pub.addMessage(messages, options.tooLong, value);
            }
            if (options.is !== undefined && value.length != options.is) {
Sergeygithub committed
68
                pub.addMessage(messages, options.notEqual, value);
Qiang Xue committed
69 70
            }
        },
71
        
72
        file: function (attribute, messages, options) {
73
            var files = getUploadedFiles(attribute, messages, options);
74
            $.each(files, function (i, file) {
75
                validateFile(file, messages, options);
76 77 78
            });
        },
        
79
        image: function (attribute, messages, options, deferred) {
80
            var files = getUploadedFiles(attribute, messages, options);
81 82
            
            $.each(files, function (i, file) {
83 84
                validateFile(file, messages, options);

85 86 87 88
                // Skip image validation if FileReader API is not available
                if (typeof FileReader === "undefined") {
                    return;
                }
89

90 91 92 93 94 95
                var def = $.Deferred(),
                    fr = new FileReader(),
                    img = new Image();
                    
                img.onload = function () {
                    if (options.minWidth && this.width < options.minWidth) {
96
                        messages.push(options.underWidth.replace(/\{file\}/g, file.name));
97 98 99
                    }
                    
                    if (options.maxWidth && this.width > options.maxWidth) {
100
                        messages.push(options.overWidth.replace(/\{file\}/g, file.name));
101 102 103
                    }
                    
                    if (options.minHeight && this.height < options.minHeight) {
104
                        messages.push(options.underHeight.replace(/\{file\}/g, file.name));
105 106 107
                    }
                    
                    if (options.maxHeight && this.height > options.maxHeight) {
108
                        messages.push(options.overHeight.replace(/\{file\}/g, file.name));
109 110 111 112 113
                    }
                    def.resolve();
                };
                
                img.onerror = function () {
Qiang Xue committed
114
                    messages.push(options.notImage.replace(/\{file\}/g, file.name));
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                    def.resolve();
                };
                
                fr.onload = function () {
                    img.src = fr.result;
                };
                
                // Resolve deferred if there was error while reading data
                fr.onerror = function () {
                    def.resolve();
                };
                
                fr.readAsDataURL(file);
                
                deferred.push(def);
130
            });
131
        
132
        },
Qiang Xue committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

        number: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value === 'string' && !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value < options.min) {
                pub.addMessage(messages, options.tooSmall, value);
            }
            if (options.max !== undefined && value > options.max) {
                pub.addMessage(messages, options.tooBig, value);
            }
        },

        range: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

157 158 159 160 161
            if (!options.allowArray && $.isArray(value)) {
                pub.addMessage(messages, options.message, value);
                return;
            }

162 163
            var inArray = true;

164
            $.each($.isArray(value) ? value : [value], function(i, v) {
165 166 167 168 169 170 171 172
                if ($.inArray(v, options.range) == -1) {
                    inArray = false;
                    return false;
                } else {
                    return true;
                }
            });

173
            if (options.not === inArray) {
Qiang Xue committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                pub.addMessage(messages, options.message, value);
            }
        },

        regularExpression: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (!options.not && !value.match(options.pattern) || options.not && value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        email: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^(.*<?)(.*)@(.*)(>?)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + punycode.toASCII(matches[2]) + '@' + punycode.toASCII(matches[3]) + matches[4];
                }
            }

            if (!valid || !(value.match(options.pattern) || (options.allowName && value.match(options.fullPattern)))) {
                pub.addMessage(messages, options.message, value);
            }
        },

        url: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (options.defaultScheme && !value.match(/:\/\//)) {
                value = options.defaultScheme + '://' + value;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3];
                }
            }

            if (!valid || !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        captcha: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            // CAPTCHA may be updated via AJAX and the updated hash is stored in body data
            var hash = $('body').data(options.hashKey);
            if (hash == null) {
                hash = options.hash;
            } else {
                hash = hash[options.caseSensitive ? 0 : 1];
            }
            var v = options.caseSensitive ? value : value.toLowerCase();
            for (var i = v.length - 1, h = 0; i >= 0; --i) {
                h += v.charCodeAt(i);
            }
            if (h != hash) {
                pub.addMessage(messages, options.message, value);
            }
        },

        compare: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var compareValue, valid = true;
            if (options.compareAttribute === undefined) {
                compareValue = options.compareValue;
            } else {
                compareValue = $('#' + options.compareAttribute).val();
            }
268 269 270 271 272

            if (options.type === 'number') {
                value = parseFloat(value);
                compareValue = parseFloat(compareValue);
            }
Qiang Xue committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286
            switch (options.operator) {
                case '==':
                    valid = value == compareValue;
                    break;
                case '===':
                    valid = value === compareValue;
                    break;
                case '!=':
                    valid = value != compareValue;
                    break;
                case '!==':
                    valid = value !== compareValue;
                    break;
                case '>':
287
                    valid = parseFloat(value) > parseFloat(compareValue);
Qiang Xue committed
288 289
                    break;
                case '>=':
290
                    valid = parseFloat(value) >= parseFloat(compareValue);
Qiang Xue committed
291 292
                    break;
                case '<':
293
                    valid = parseFloat(value) < parseFloat(compareValue);
Qiang Xue committed
294 295
                    break;
                case '<=':
296
                    valid = parseFloat(value) <= parseFloat(compareValue);
Qiang Xue committed
297 298 299 300 301 302 303 304 305 306 307
                    break;
                default:
                    valid = false;
                    break;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        }
    };
308

309
    function getUploadedFiles(attribute, messages, options) {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        var files = $(attribute.input).get(0).files;
        if (!files) {
            messages.push(options.message);
            return [];
        }

        if (files.length === 0) {
            if (!options.skipOnEmpty) {
                messages.push(options.uploadRequired);
            }
            return [];
        }

        if (options.maxFiles && options.maxFiles < files.length) {
            messages.push(options.tooMany);
            return [];
        }

        return files;
    }

    function validateFile(file, messages, options) {
        if (options.extensions && options.extensions.length > 0) {
            var index, ext;

            index = file.name.lastIndexOf('.');

            if (!~index) {
                ext = '';
            } else {
                ext = file.name.substr(index + 1, file.name.length).toLowerCase();
            }

            if (!~options.extensions.indexOf(ext)) {
                messages.push(options.wrongExtension.replace(/\{file\}/g, file.name));
            }
        }

        if (options.mimeTypes && options.mimeTypes.length > 0) {
            if (!~options.mimeTypes.indexOf(file.type)) {
                messages.push(options.wrongMimeType.replace(/\{file\}/g, file.name));
            }
        }

        if (options.maxSize && options.maxSize < file.size) {
            messages.push(options.tooBig.replace(/\{file\}/g, file.name));
        }

        if (options.minSize && options.minSize > file.size) {
            messages.push(options.tooSmall.replace(/\{file\}/g, file.name));
        }
    }

Qiang Xue committed
363
    return pub;
Qiang Xue committed
364
})(jQuery);