如何在mvc 2 app中验证2种不同情况下的属性?

时间:2012-07-31 21:56:45

标签: c# .net validation asp.net-mvc-2 asp.net-mvc-validation

请帮助我使用asp.net MVC 2应用程序。

我上课了:

public class Account
{
    [Required(....)]
    [RegularExpression("....")]
    public string AccountCode{ get; set; } 

    public string BankName{ get;  set; } 
}

还有一个:

public class BankPageModel
{
    public bool AccountRequired {get; set; }
    public Account NewAccount {get;set;}
}

想象一下,我的页面和表单上有2个文本框(AccountCode和BankName)和复选框(AccountRequired)。因此,当我发布表单时,如果选中复选框,我想验证AccountCode是否必需并适合正则表达式。但如果没有选中,我只想忽略这些文本框并发布表单。但是当时不能使用Required和RegularExpression属性,它们正在阻止它。我可以创建类属性,但如果我有更多具有类似验证的文本框,我不想为每个文本框创建类属性... 你怎么看?提前谢谢。

3 个答案:

答案 0 :(得分:1)

您不需要使用DataAnnotations来执行验证,它们只会使常见验证方案更容易(并且您也可以免费获得客户端JavaScript验证)。

您可以随时在Controller操作中使用C#代码执行验证,如下所示:

public ViewResult BankPageAdd(BankPageModel model)
{
    if(model.AccountRequired &&
        (String.IsNullOrWhiteSpace(model.Account.AccountCode) || !Regex.IsMatch(model.Account.AccountCode, "PATTERN HERE"))
        ModelState.AddModelError("NewAccount.AccountCode", "ERROR MESSAGE HERE");

    //remainder of your controller action code here
}

答案 1 :(得分:1)

在服务器端执行此操作的最佳方法是让模型实现 IValidatableObject ,然后执行以下操作:

public class BankPageModel : System.ComponentModel.DataAnnotations.IValidatableObject
{
    public bool AccountRequired { get; set; }
    public Account NewAccount { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // only perform validation here if account required is checked
        if (this.AccountRequired)
        {
            // check your regex here for account
            if (!RegEx.IsMatch(this.NewAccount.AccountCode, "EXPRESSION"))
            {
                yield return new ValidationResult("Error");
            }
        }
    }
}     

以这种方式做事有助于保持控制器的精益,并将所有验证逻辑封装在模型中。此方法也可以通过unobtrusive javascript验证客户端。

答案 2 :(得分:0)

javaScript版本:

function validateAccountCode() {
        var bCkd = document.getElementById("ckbxAccountRequired").checked;

        if (bCkd) {
           var accountCode = document.forms[0].elements["AccountCode"].value;
            if(!accountCode.match(yourRegEx) || accountCode==""){
               alert('Please fill in the Account Code');
               return false;
            }
            return true;
        }
        return true;
    }