2

我正在使用 asp.net mvc 4 我在我的模型中使用 [maxlength(2)] 但它不适用于客户端验证我是 asp.net mvc 的新手。这是我的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace RestrauntsMVC.Models
{
  public class Restraunts
  {

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [MaxLength(2),MinLength(1)]
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
  }
}
4

2 回答 2

7

我发现答案 myslef 它适用于 Maxlength 和 minlength 用于字符串而不是整数。

using System;
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  
namespace RestrauntsMVC.Models
{
public class Restraunts
{

    public int id { get; set; }
    [Required]
    public string name { get; set; }
    [Required]
    [Range(1,10,ErrorMessage="Rating must between 1 to 10")]        
    public int rating { get; set; }
    [Required]
    public string location { get; set; }
}
}
于 2012-11-29T17:08:48.963 回答
2

就像其他提及仅适用于字符串一样,那么编写自己的ValidationAttribute怎么样?

using System.ComponentModel.DataAnnotations;

internal class MaxDigitsAttribute : ValidationAttribute
{
    private int Max,
                Min;

    public MaxDigitsAttribute(int max, int min = 0)
    {
        Max = max;
        Min = min;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (!IsValid(value))
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }

    public override bool IsValid(object value)
    {
        // you could do any custom validation you like
        if (value is int)
        {
            var stringValue = "" + (int)value;
            var length = stringValue.Length;
            if (length >= Min && length <= Max)
                return true;
        }

        return false;
    }
}
于 2014-03-21T16:08:12.493 回答