using System. ComponentModel. DataAnnotations;
[
{
}
}
[
{
}
}
[
{
List<Errors> errors = new List<Errors>();
List<string> ErrorLst = new List<string>();
{
}
{
Key = "Email",
});
}
{
List<string> ErrorLst = new List<string>();
{
}
{
Key = "Password",
});
}
}
}
{
}
{
[Required
[
[Required
[Range
[Required
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",ErrorMessage ="
[Range
[System
[Required
[Required]
[
{
{
}
}
}
//
{
{
_maxWords =
}
{
{
var valueAsString = value.ToString();
if (valueAsString.Length < _maxWords)
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(errorMessage);
}
}
return ValidationResult.Success;
}
}
// remove fields from Model
if (objEventInfo.AccTypeCode == "Business"){
ModelState.Remove("Age");
ModelState.Remove("Gender");
ModelState.Remove("PersonLimit");
ModelState.Remove("PerAccountLimit");
ModelState.Remove("WaitingListLimit");
}
// loop and identify errors on model state
foreach (ModelState modelState in ViewData.ModelState.Values){
foreach (ModelError error in modelState.Errors)
{
}
}
////////////////////////////////////////////////////////
Isolate object and validate object
api
[HttpGet] public HttpResponseMessage ModelValidation2() { var x = new Product { Id = 1, Name = "", Price = 123, Weight = -789 }; var e = new List<Errors>(); if (!IsValidate.IsValied(x, out e)) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, JsonConvert.SerializeObject(e)); } return Request.CreateErrorResponse(HttpStatusCode.OK, "ok"); }
public class Errors { public string Field { get; set; } public string Error { get; set; } } public class IsValidate { public static bool IsValied(object x, out List<Errors> e) { ValidationContext context = new ValidationContext(x, null, null); IList<ValidationResult> errors = new List<ValidationResult>(); e = new List<Errors>(); if (!Validator.TryValidateObject(x, context, errors, true)) { foreach (ValidationResult result in errors) { string d = result.ErrorMessage; e.Add(new Errors { Error = result.ErrorMessage, Field = result.MemberNames.ToList().FirstOrDefault() }); } return false; } return true; } }///////////////////////////////////////////////
Fluant validation
using FluentValidation;
using FluentValidation.Results;
using FluentValidation.Validators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FluantValidation
{
public class Student {
public string Name { get; set; } // requted
public string Email { get; set; } // email
public string Password { get; set; } // length 3-5
public string ConfirmPassword { get; set; } // same to password
public DateTime DOB { get; set; } // past date
public string Nic { get; set; } // 880240684V
public string PasswordHint { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Login();
Register();
Console.Read();
}
private static void Login()
{
var x = new StudentLoginValidation().Validate(new Student
{
Email = "",
Password = "123"
});
if (!x.IsValid)
{
foreach (var item in x.Errors)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("model is valied");
}
}
private static void Register()
{
var x = new RegisterValidation().Validate(new Student
{
Email = "",
Password = "123",
PasswordHint = "123",
ConfirmPassword="1234",
Age= -1,
DOB = new DateTime(2016,1,1),
Nic="880240684V",
Name=""
});
if (!x.IsValid)
{
foreach (var item in x.Errors)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("model is valied");
}
}
}
public class StudentLoginValidation: AbstractValidator<Student> {
public StudentLoginValidation()
{
RuleFor(p => p.Email).NotNull().NotEmpty().WithMessage("email requred");
RuleFor(p => p.Password).NotNull().NotEmpty().WithMessage("email requred");
}
}
public class RegisterValidation : AbstractValidator<Student>
{
public RegisterValidation()
{
RuleFor(p => p.Email).EmailAddress().WithMessage("enter valied email address");
RuleFor(p => p.Password).Length(3, 10).WithMessage("password must be char 3-10");
RuleFor(p => p.Name).NotEmpty().NotNull().WithMessage("name must be there");
RuleFor(p => p.Password).Equal(p => p.ConfirmPassword).WithMessage("2 password are not same");
RuleFor(p => p.Age).GreaterThan(0).WithMessage("age must be gratter than 0");
RuleFor(p => p.PasswordHint).Equal(p => p.Password)
.WithMessage("password hint not must be password {0}", p => p.PasswordHint);
RuleFor(p => p.Nic).Must(IsNic).WithMessage("invalied nic");
}
private bool IsNic(string nic)
{
bool isvalied = true;
double tempVal = 0.0;
if (nic.Length != 10)
{
isvalied = false;
}
else if (double.TryParse(nic.Substring(0, nic.Length - 1), out tempVal))
{
isvalied = false;
}
else if (nic.Substring(nic.Length - 1, 1).ToLower() != "v")
{
isvalied = false;
}
return isvalied;
}
}
}
No comments:
Post a Comment