繁体   English   中英

MVC 5 ASP.NET 街道地址验证

[英]MVC 5 ASP.NET Street Address Validation

我有以下 Profile 类:

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>

我将如何使街道地址的验证取决于配置文件中的其他值/属性?

如果用户未输入街道、城市、州或邮政编码,则应允许用户提交表单。 但是如果用户只进入一个状态而其他三个都不进入,则不应允许。

要么全部填满,要么根本没有。

我该怎么做?

在谷歌搜索了一下之后,我尝试了 [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);
        }


    }

我想我想通了,但我不确定这是否是“正确”的方法?

这种方式不是正确的方式,因为 || 即使所有条件都为假,也将返回假,如果其中一个条件为真,则返回真。 这就是我知道这会起作用的方式

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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM