About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

MVC-Custom Model Validate

MVC - Custom Model Validate


1. Example 1

Add an attribute to validate your MVC model

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class ModelValidateAttribute : ValidationAttribute
{

private string _defaultErrorMessage = string.Empty;

public override string FormatErrorMessage(string name)
{
return _defaultErrorMessage;
}

public override bool IsValid(object value)
{
if (value is ImodelValidator)
{
return (value as ImodelValidator).Valid(out _defaultErrorMessage);
}
else
{
throw new NotImplementedException("ImodelValidator Not Implemented");
}
return false;
}
}

Add an intrface
interface ImodelValidator
{
bool Valid(out string errorMessage);
}
Impliment interface to your model

[ModelValidate()]
public class RegisterModel : ImodelValidator
{
[Required]
[DisplayName("User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email address")]
public string Email { get; set; }

[Required]
[ValidatePasswordLength]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }

[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }

#region ImodelValidator Members

public bool Valid(out string errorMessage)
{
if (Password.Contains('.'))
{
errorMessage = "invalid char";
return false;
}
else if (Password != ConfirmPassword)
{
errorMessage = "The password and confirmation password do not match.";
return false;
}
else if(!IsRegister(Email))
{
errorMessage = "Email already Registerd with website";
return false;
}
else
{
errorMessage = string.Empty;
return true;
}
return false;
}

#endregion
private bool IsRegister(string email)
{
return false;
} }
#endregion





2. Example 2

3. Example 3

No comments :