ASP.NET MVC2 - 在服务器端验证之前从表单提交修剪空格?

时间:2011-01-07 17:49:58

标签: asp.net-mvc-2 attributes validation trim

如果我添加验证属性:

public class ProductDownloadListModel
{        
    //xxxxx-xxxxx-xxxxx
    [Required]
    [StringLength(17)]
    public string PSN { get; set; }
    public DateTime PsnExpirationDate { get; set; } 
    public DataTable Downloads { get; set; } 

}

并且用户输入一个17个字符的字符串,但最后包含空格,我收到验证错误,因为该字符串大于[StringLength(17)]属性指定的字符串。我怎么能阻止这个?我希望在提交之前不必让javaScript修剪字符串。

2 个答案:

答案 0 :(得分:5)

对你的PSN进行修剪。

public string PSN
{
    get
    {
        return (this.psn == null) ? string.Empty : this.psn;
    }
    set
    {
        this.psn = (value == null || value.Trim().Length == 0) ? null :value.Trim();
    }
}

答案 1 :(得分:1)

为什么不在html输入上使用maxlength属性?

http://www.w3schools.com/tags/att_input_maxlength.asp