实体框架 - 使用数据注释进行验证(服务器+客户端、jquery),无需 MVC?

发布于 2024-09-18 16:29:38 字数 2268 浏览 8 评论 0原文

有几个教程解释了如何使用 MVC 框架使用 EF 数据注释进行表单验证。并在客户端使用jquery。

请参阅例如: http://dotnetaddict.dotnetdevelopersjournal.com/clientvalidation_mvc2.htm

我想实现相同的效果,但不使用 MVC/MVC2。

我想构建一个经典的 asp.net 站点,创建实体模型,创建包含验证(必需、正则表达式等)的部分类。

我创建了实体模型和部分类,包括数据注释。我可以将新记录添加到数据库中。

我怀念的是验证。现在,即使字段无效,我也可以将记录添加到数据库,我想得到错误,如果可能的话,我想使用 jquery 进行客户端验证(在 MVC 中,您只需添加 <% Html .EnableClientValidation(); %> 到视图...)。

你能帮助我吗?或者给我指出一些很好的在线资源来解释这一点?

多谢。

编辑:我在这里找到了一些东西:

我如何告诉数据注释验证器也验证复杂的子属性?

我有一个名为“User”的实体,并且我创建了一个部分类,如下所示:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MySite.Models
{
    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
    }

    public class UserMetaData
    {
        [Required(ErrorMessage = "Username Required")]
        [DisplayName("Username")]
        public string Username{ get; set; }

        [DisplayName("Password")]
        [Required(ErrorMessage = "Password Required")]
        [RegularExpression(@"^[^;>;&;<;%?*!~'`;:,."";+=|]{6,10}$", ErrorMessage = "The password must be between 6-10 characters and contain 2 digits")]
        public string Password{ get; set; }
    }
}

在后面的代码中在我的页面中,我放置了类似的“isValid”检查,如上面提到的链接:

var validationContext = new ValidationContext(person, null, null);
var validationResults = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(userToAdd, validationContext, validationResults);

if (isValid)
{
savetoDB();
}

但是当我调试时...“isValid”始终为“true”,即使我将字段保留为空。帮助:-S

EDIT2:

它始终为“true”,因为我正在填充“用户”属性,如下所示:

User userToAdd = new User();
userToAdd.Username = txtUsername.Text;
userToAdd.Password = txtPassword.Text;

我更改了对象:从“User”到“UserMetaData”(User userToAdd = new UserMetaData();)然后验证工作(“假”,以防不遵守正则表达式)...但仍然很奇怪...然后我应该创建另一个“用户”对象并再次填充它...不是很干净的...

there are several tutorials that explain how to use EF data annotation for forms validation using the MVC framework. And to use jquery for the client side.

See e.g.: http://dotnetaddict.dotnetdevelopersjournal.com/clientvalidation_mvc2.htm

I would like to achieve the same, but without using MVC/MVC2.

I want to build a classic asp.net site, create the Entities Model, create my partial classes that include the validation (required, regex etc.).

I created the entities model and the partial classes including the data annotations. I can add new records to the DB.

What I miss is the validation. Now I can add records to the DB even if the fields are not valid, I would like to get the errors, and if possible I would like to use jquery for the client validation (in MVC you just add <% Html.EnableClientValidation(); %> to the view...).

Can you help me? Or point me to some good online resources that explain this?

Thanks a lot.

EDIT: I found something here:

How can I tell the Data Annotations validator to also validate complex child properties?

I have an Entity called "User" and I created a partial class as follows:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MySite.Models
{
    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
    }

    public class UserMetaData
    {
        [Required(ErrorMessage = "Username Required")]
        [DisplayName("Username")]
        public string Username{ get; set; }

        [DisplayName("Password")]
        [Required(ErrorMessage = "Password Required")]
        [RegularExpression(@"^[^;>;&;<;%?*!~'`;:,."";+=|]{6,10}$", ErrorMessage = "The password must be between 6-10 characters and contain 2 digits")]
        public string Password{ get; set; }
    }
}

In the code behind of my page I've put a similar "isValid" check as in the above mentioned link:

var validationContext = new ValidationContext(person, null, null);
var validationResults = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(userToAdd, validationContext, validationResults);

if (isValid)
{
savetoDB();
}

But when I debug... "isValid" is always "true", even if I leave the fields null. Help :-S

EDIT2:

It was always "true" because I was filling the "user" properties, as follows:

User userToAdd = new User();
userToAdd.Username = txtUsername.Text;
userToAdd.Password = txtPassword.Text;

I changed the object: from "User" to "UserMetaData" (User userToAdd = new UserMetaData();) then the validation works ("false" in case the regex is not respected) ... but still, quite weird... then I should create another "User" object and fill it again... not very clean...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离旧人 2024-09-25 16:29:38

您现在可能已经找到了解决方案或继续前进,但我创建了一个开源项目来完成此任务 - 使用数据注释属性和 jQuery Validate 进行 MVC 样式验证。

http://xvalwebforms.codeplex.com

您会对 jQuery.Validate 分支感兴趣。它还不太完整,但已经非常接近了。以下是演示项目的示例:

模型

public class Booking : IValidatableObject
{
    [Required(ErrorMessage = "Client name is required.")]
    [StringLength(15, ErrorMessage = "Client name must be less than 15 characters.")]
    public string ClientName { get; set; }

    [Range(1, 20, ErrorMessage = "Number of guests must be between 1 and 20.")]
    public int NumberOfGuests { get; set; }

    [Required(ErrorMessage = "Arrival date is required.")]
    [DataType(DataType.Date, ErrorMessage = "Arrival date is invalid.")]
    public DateTime ArrivalDate { get; set; }

    [Required(ErrorMessage = "Smoking type is requried.")]
    public SmokingType SmokingType { get; set; }

    [Required(ErrorMessage = "Email address is required.")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Email address is invalid.")]
    public string EmailAddress { get; set; }

    #region IValidatableObject Members

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (ArrivalDate == DateTime.MinValue)
        {
            yield return new ValidationResult("Arrival date is required.", new[] {"ArrivalDate"});
        }

        // Business rule: Can't place bookings on Sundays
        if (ArrivalDate.DayOfWeek == DayOfWeek.Sunday)
        {
            yield return new ValidationResult("Bookings are not permitted on Sundays.", new[] {"ArrivalDate"});
        }
    }

    #endregion
}

ASPX 标记

    <fieldset class="booking">
        <legend>Booking</legend>
        <asp:ValidationSummary ID="valSummary" runat="server" CssClass="ui-state-error" />
        <val:ModelValidator ID="valBooking" runat="server" CssClass="validator" Display="Dynamic"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtClientName">
            Your name:</label>
        <asp:TextBox ID="txtClientName" runat="server" />
        <val:ModelPropertyValidator ID="valClientName" runat="server" CssClass="validator"
            ControlToValidate="txtClientName" Display="Dynamic" PropertyName="ClientName"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtNumberOfGuests">
            Number of guests:</label>
        <asp:TextBox ID="txtNumberOfGuests" runat="server" />
        <val:ModelPropertyValidator ID="valNumberOfGuests" runat="server" CssClass="validator"
            ControlToValidate="txtNumberOfGuests" Display="Dynamic" PropertyName="NumberOfGuests"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtArrivalDate">
            Arrival date:</label>
        <asp:TextBox ID="txtArrivalDate" runat="server" CssClass="date-picker" />
        <val:ModelPropertyValidator ID="valArrivalDate" runat="server" CssClass="validator"
            ControlToValidate="txtArrivalDate" Display="Dynamic" PropertyName="ArrivalDate"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtEmailAddress">
            Email address:</label>
        <asp:TextBox ID="txtEmailAddress" runat="server" />
        <val:ModelPropertyValidator ID="valEmailAddress" runat="server" CssClass="validator"
            ControlToValidate="txtEmailAddress" Display="Dynamic" PropertyName="EmailAddress"
            ModelType="xVal.WebForms.Demo.Booking" />
        <div>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></div>
    </fieldset>

代码隐藏

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (!IsValid)
    {
        return;
    }

    if (txtNumberOfGuests.Text.Length == 0)
    {
        txtNumberOfGuests.Text = "1";
    }

    Booking booking = new Booking
                          {
                              ClientName = txtClientName.Text,
                              NumberOfGuests = Convert.ToInt32(txtNumberOfGuests.Text),
                              ArrivalDate = Convert.ToDateTime(txtArrivalDate.Text),
                              EmailAddress = txtEmailAddress.Text
                          };

    BookingManager.PlaceBooking(booking);
}

You've probably found a solution or moved on by now, but I created an open source project that does exactly this - MVC style validation with Data Annotations attributes and jQuery Validate.

http://xvalwebforms.codeplex.com

You'll be interested in the jQuery.Validate branch. Its not quite complete yet, but very close. Here's an example from the demo project:

Model

public class Booking : IValidatableObject
{
    [Required(ErrorMessage = "Client name is required.")]
    [StringLength(15, ErrorMessage = "Client name must be less than 15 characters.")]
    public string ClientName { get; set; }

    [Range(1, 20, ErrorMessage = "Number of guests must be between 1 and 20.")]
    public int NumberOfGuests { get; set; }

    [Required(ErrorMessage = "Arrival date is required.")]
    [DataType(DataType.Date, ErrorMessage = "Arrival date is invalid.")]
    public DateTime ArrivalDate { get; set; }

    [Required(ErrorMessage = "Smoking type is requried.")]
    public SmokingType SmokingType { get; set; }

    [Required(ErrorMessage = "Email address is required.")]
    [DataType(DataType.EmailAddress, ErrorMessage = "Email address is invalid.")]
    public string EmailAddress { get; set; }

    #region IValidatableObject Members

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (ArrivalDate == DateTime.MinValue)
        {
            yield return new ValidationResult("Arrival date is required.", new[] {"ArrivalDate"});
        }

        // Business rule: Can't place bookings on Sundays
        if (ArrivalDate.DayOfWeek == DayOfWeek.Sunday)
        {
            yield return new ValidationResult("Bookings are not permitted on Sundays.", new[] {"ArrivalDate"});
        }
    }

    #endregion
}

ASPX Markup

    <fieldset class="booking">
        <legend>Booking</legend>
        <asp:ValidationSummary ID="valSummary" runat="server" CssClass="ui-state-error" />
        <val:ModelValidator ID="valBooking" runat="server" CssClass="validator" Display="Dynamic"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtClientName">
            Your name:</label>
        <asp:TextBox ID="txtClientName" runat="server" />
        <val:ModelPropertyValidator ID="valClientName" runat="server" CssClass="validator"
            ControlToValidate="txtClientName" Display="Dynamic" PropertyName="ClientName"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtNumberOfGuests">
            Number of guests:</label>
        <asp:TextBox ID="txtNumberOfGuests" runat="server" />
        <val:ModelPropertyValidator ID="valNumberOfGuests" runat="server" CssClass="validator"
            ControlToValidate="txtNumberOfGuests" Display="Dynamic" PropertyName="NumberOfGuests"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtArrivalDate">
            Arrival date:</label>
        <asp:TextBox ID="txtArrivalDate" runat="server" CssClass="date-picker" />
        <val:ModelPropertyValidator ID="valArrivalDate" runat="server" CssClass="validator"
            ControlToValidate="txtArrivalDate" Display="Dynamic" PropertyName="ArrivalDate"
            ModelType="xVal.WebForms.Demo.Booking" />
        <label for="txtEmailAddress">
            Email address:</label>
        <asp:TextBox ID="txtEmailAddress" runat="server" />
        <val:ModelPropertyValidator ID="valEmailAddress" runat="server" CssClass="validator"
            ControlToValidate="txtEmailAddress" Display="Dynamic" PropertyName="EmailAddress"
            ModelType="xVal.WebForms.Demo.Booking" />
        <div>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /></div>
    </fieldset>

Code behind

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (!IsValid)
    {
        return;
    }

    if (txtNumberOfGuests.Text.Length == 0)
    {
        txtNumberOfGuests.Text = "1";
    }

    Booking booking = new Booking
                          {
                              ClientName = txtClientName.Text,
                              NumberOfGuests = Convert.ToInt32(txtNumberOfGuests.Text),
                              ArrivalDate = Convert.ToDateTime(txtArrivalDate.Text),
                              EmailAddress = txtEmailAddress.Text
                          };

    BookingManager.PlaceBooking(booking);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文