我正在使用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; }
}
}
答案 0 :(得分:6)
我发现答案myslef它的工作原理是Maxlength,minlength是String不是整数。
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; }
}
}
答案 1 :(得分:1)
像其他提到的只是字符串所以如何编写自己的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;
}
}