问题
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...
回答1:
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);
}
来源:https://stackoverflow.com/questions/3699038/entity-framework-validation-server-clientside-jquery-with-data-annotation