views:

179

answers:

0

Hi,

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...