实体框架 - 验证(服务器+客户方,jQuery的)数据注解,没有MVC? [英] Entity Framework - Validation (server + clientside, jquery) with data annotations, WITHOUT MVC?
问题描述
有几个教程解释了如何使用EF数据注解使用MVC框架的形式验证。并使用jQuery的客户端。
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.
请参阅如: http://dotnetaddict.dotnetdevelopersjournal.com/clientvalidation_mvc2.htm
我想实现相同的,但没有使用MVC / MVC2。
I would like to achieve the same, but without using MVC/MVC2.
我想建立一个经典的asp.net网站,创建的实体模型,创建我的部分类,包括验证(必填,正则表达式等)。
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.
我怀念的是验证。现在我可以将记录添加到数据库,即使这些字段是无效的,我想获得的错误,如果可能的话,我想使用jQuery客户端验证(MVC中你只需要添加&LT ;%Html.EnableClientValidation();%方式>
来的观点......)
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?
非常感谢。
修改:我发现这里的东西:
EDIT: I found something here:
<一个href=\"http://stackoverflow.com/questions/2493800/how-can-i-tell-the-data-annotations-validator-to-also-validate-complex-child-prop\">How我可以告诉数据注释验证器也验证复杂的子属性?
我有一个实体,称为用户和我创建了一个局部类,如下所示:
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; }
}
}
在我的网页背后的code,我已经把类似的IsValid的签在上面提到的链接:
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();
}
但是,当我调试......的isValid始终是真,即使我离开的字段为空。说明:-S
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;
我改变了对象:从用户到UserMetaData(用户userToAdd =新UserMetaData();
),那么验证工作(假的情况下,正则表达式是不尊重)......但尽管如此,相当怪异......那么我应该创建另一个用户对象,并再次填写...不是很干净...
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...
推荐答案
您可能已经找到了解决办法,或搬到现在,但我创建了一个开源项目,正是这一点 - MVC风格与验证数据注释属性和jQuery的验证。
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.$c$cplex.com
您会感兴趣的jQuery.Validate分支。它不是相当齐全还,但非常接近。下面是从演示项目的例子:
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:
型号
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>
后面的 code
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);
}
这篇关于实体框架 - 验证(服务器+客户方,jQuery的)数据注解,没有MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!