我有以下个人资料类:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MyValidation.Models
{
public class Profile : ValidationAttribute
{
[Required]
public string Name
{
get;
set;
}
[Required]
[Range(5, 99)]
public int Age
{
get;
set;
}
public string Street
{
get;
set;
}
public string City
{
get;
set;
}
public string Zip
{
get;
set;
}
public string State
{
get;
set;
}
}
}
观看:
@model MyValidation.Models.Profile
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>@Html.ValidationMessageFor(x => x.Name)</p>
<p>Your Full Name: @Html.TextBoxFor(x => x.Name)</p>
<p>@Html.ValidationMessageFor(x => x.Age)</p>
<p>Your current age: @Html.TextBoxFor(x => x.Age)</p>
<p>Your full address:
<br />@Html.TextBoxFor(x => x.Street)</p>
@:City: @Html.TextBoxFor(x => x.City)
@:State: @Html.TextBoxFor(x => x.State)
@:Zip Code: @Html.TextBoxFor(x => x.Zip)
<input type="submit" value="Submit Form" />
}
</div>
</body>
</html>
我如何制作以便街道地址的验证取决于个人资料中的其他值/属性?
如果用户未输入街道,城市,州或ZIP,则应允许用户提交表单。但是,如果用户只输入一个状态而不输入其他3个状态,则不应该允许它。
它要么全部填写,要么根本没有。
我该怎么做?
在谷歌搜索后,我尝试了[Compare()],但这不起作用
修改
public class HomeController : Controller
{
// GET: Home
public ActionResult Index(Profile profile)
{
Profile _profile = profile ?? new Profile();
if (string.IsNullOrEmpty(_profile.Street) || string.IsNullOrEmpty(_profile.State))
ModelState.AddModelError("Address", "All Address fields have to be empty, OR full");
return View(_profile);
}
}
我想我已经明白了,但我不确定这是否是“正确”的做法?
答案 0 :(得分:0)
那是不正确的方法,因为||即使所有条件都为假,也将返回false;如果其中一个条件为真,则将返回true。 我知道这是可行的
if((!string.IsNullOrEmpty(_profile.Street) || !string.IsNullOrEmpty(_profile.State) || !string.IsNullOrEmpty(_profile.City) || !string.IsNullOrEmpty(_profile.Zip)) && (string.IsNullOrEmpty(_profile.Street) || string.IsNullOrEmpty(_profile.State) || string.IsNullOrEmpty(_profile.City) || string.IsNullOrEmpty(_profile.Zip)))
{
ModelState.AddModelError("Address", "All Address fields have to be empty, OR full");
}