MVC validation 13-2 Properties Enter at least one item

Source: Internet
Author: User

Sometimes we want at least one of the 2 attributes to be required, such as:

using Car.Test.Portal.Extension;
namespace Car.Test.Portal.Models
{
     Public class Person
    {
         Public int Id {get; set;}
         Public string telephone {get; set;}
         Public string Address {get; set;}
    }
}

If you have one of the telephone and address attributes that is required, you need to customize the attribute.

-Custom Atleastoneattribute attribute, derived from Validationattribute class, and implements Iclientvalidatable interface

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using SYSTEM.WEB.MVC;
namespace Car.Test.Portal.Extension
{
    true true)]
     Public Sealed class Atleastoneattribute:validationattribute, iclientvalidatable
    {
         Public string private set; }
         Public string private set; }
         Public Atleastoneattribute (stringstring secondproperty)
        {
            Primaryproperty = Primaryproperty;
            Secondaryproperty = Secondproperty;
        }
         Public Override string Formaterrormessage (string name)
        {
            return string this. Errormessagestring, Primaryproperty, Secondaryproperty);
        }
         Public Override BOOL IsValid (objectvalue)
        {
            PropertyDescriptorCollection properties = typedescriptor.getproperties (value);
            Object true / * ignoreCase */). GetValue (value);
            Object true / * ignoreCase */). GetValue (value);
            if NULL null)
            {
                return true;
            }
            Else
            {
                return false;
            }
            Return (Primaryvalue! = NULL | | Secondaryvalue! = NULL);
            Slightly change the following can also compare 2 properties are equal
            if (!primaryvalue.equals (Secondaryvalue))
                return true;
            Else
                return false;
        }
         Public System.collections.generic.ienumerable<modelclientvalidationrule> Getclientvalidationrules (ModelMetadata metadata, ControllerContext context)
        {
            string errormessage = Formaterrormessage ("");
            New Modelclientvalidationrule ()
            {
                "Atleastone",
                ErrorMessage = errormessage
            };
            Rule. Validationparameters.add ("PRIMARY"this. Primaryproperty);
            Rule. Validationparameters.add ("secondary"this. Secondaryproperty);
            yield return rule;
        }
    }
}

-Hit the custom feature Atleastoneattribute on the class

using Car.Test.Portal.Extension;
namespace Car.Test.Portal.Models
{
    [Atleastone ("Telephone""Address""telephone and address at least one item ~ ~")]
     Public class Person
    {
         Public int Id {get; set;}
         Public string telephone {get; set;}
         Public string Address {get; set;}
    }
}

-personcontroller

     Public class Personcontroller:controller
    {
         Public ActionResult Index ()
        {
            return View (new person ());
        }
        [HttpPost]
        [Validateantiforgerytoken]
         Public ActionResult Index (person person)
        {
            if (Modelstate.isvalid)
            {
                Todo:
                return Content ("OK");
            }
            Else
            {
                return View (person);
            }
        }
    }

-person/index.cshtml

You need to register your custom features with the jquery-related class library.

@model Car.Test.Portal.Models.Person
<body>
    <script src="~/scripts/jquery-1.10.2.js"></script>
    <script src="~/scripts/jquery-migrate-1.2.1.min.js"></script>
    <script src="~/scripts/jquery.validate.min.js"></script>
    <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
    @*<script src="~/scripts/atleastone.js"></script>*@
    <style type="Text/css">
        . validation-summary-errors {
            color:red;
        }
    </style>
    <script type="Text/javascript">
        JQuery.validator.addMethod ("Atleastone", function (valueparams) {
            params. Primary;
            params. Secondary;
            if (Primaryproperty.length > 0 | | secondaryproperty.length > 0) {
                return true;
            Else {
                return false;
            }
        });
        JQuery.validator.unobtrusive.adapters.add ("Atleastone", ["PRIMARY""secondary"], function (options) {
            options.rules["Atleastone"] = {
                Primary:options. params. Primary,
                Secondary:options. params. Secondary
            };
            options.messages["Atleastone"] = options.message;
        });
        
    </script>
    
    @using (Html.BeginForm ()) {
        @Html. AntiForgeryToken ()
        @Html. ValidationSummary (true)
       
    
        <fieldset>
            <legend>Person</legend>
    
            class="Editor-label">
                @Html. labelfor (model = model. Telephone)
            </div>
            class="Editor-field">
                @Html. editorfor (model = model. Telephone)
                @Html. validationmessagefor (model = model. Telephone)
            </div>
    
            class="Editor-label">
                @Html. labelfor (model = model. Address)
            </div>
            class="Editor-field">
                @Html. editorfor (model = model. Address)
                @Html. validationmessagefor (model = model. Address)
            </div>
    
            <p>
                <input type="Submit"value="Create" />
            </p>
        </fieldset>
    }
</body>

-Effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.