1 /* ****************************************************************************
\r
3 * Copyright (c) Microsoft Corporation. All rights reserved.
\r
5 * This software is subject to the Microsoft Public License (Ms-PL).
\r
6 * A copy of the license can be found in the license.htm file included
\r
7 * in this distribution.
\r
9 * You must not remove this notice, or any other, from this software.
\r
11 * ***************************************************************************/
\r
13 namespace System.Web.Mvc {
\r
15 using System.Collections.Generic;
\r
16 using System.Globalization;
\r
18 using System.Web.Mvc.Resources;
\r
20 public class ClientDataTypeModelValidatorProvider : ModelValidatorProvider {
\r
22 private static readonly HashSet<Type> _numericTypes = new HashSet<Type>(new Type[] {
\r
23 typeof(byte), typeof(sbyte),
\r
24 typeof(short), typeof(ushort),
\r
25 typeof(int), typeof(uint),
\r
26 typeof(long), typeof(ulong),
\r
27 typeof(float), typeof(double), typeof(decimal)
\r
30 public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {
\r
31 if (metadata == null) {
\r
32 throw new ArgumentNullException("metadata");
\r
34 if (context == null) {
\r
35 throw new ArgumentNullException("context");
\r
38 return GetValidatorsImpl(metadata, context);
\r
41 private static IEnumerable<ModelValidator> GetValidatorsImpl(ModelMetadata metadata, ControllerContext context) {
\r
42 Type type = metadata.ModelType;
\r
43 if (IsNumericType(type)) {
\r
44 yield return new NumericModelValidator(metadata, context);
\r
48 private static bool IsNumericType(Type type) {
\r
49 Type underlyingType = Nullable.GetUnderlyingType(type); // strip off the Nullable<>
\r
50 return _numericTypes.Contains(underlyingType ?? type);
\r
53 internal sealed class NumericModelValidator : ModelValidator {
\r
54 public NumericModelValidator(ModelMetadata metadata, ControllerContext controllerContext)
\r
55 : base(metadata, controllerContext) {
\r
58 public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
\r
59 ModelClientValidationRule rule = new ModelClientValidationRule() {
\r
60 ValidationType = "number",
\r
61 ErrorMessage = MakeErrorString(Metadata.GetDisplayName())
\r
64 return new ModelClientValidationRule[] { rule };
\r
67 private static string MakeErrorString(string displayName) {
\r
68 // use CurrentCulture since this message is intended for the site visitor
\r
69 return String.Format(CultureInfo.CurrentCulture, MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric, displayName);
\r
72 public override IEnumerable<ModelValidationResult> Validate(object container) {
\r
73 // this is not a server-side validator
\r
74 return Enumerable.Empty<ModelValidationResult>();
\r