Sunday, May 22, 2016

Validation


using System.ComponentModel.DataAnnotations;


[HttpGet]
        public JsonResult Access(Person p)
        {
            if (!ModelState.IsValid){
                return Json(ModelState, JsonRequestBehavior.AllowGet);
            }
            return Json("succeess", JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult CheckedMyErrorMessage(Person p) {
            bool isValied = true;
            string message = "";
            if (ModelState["MyError"].Errors.Count!=0)
            {
                isValied = false;
                message = ModelState["MyError"].Errors[0].ErrorMessage;
            }
            return (isValied) ? Json("success",JsonRequestBehavior.AllowGet) : Json(message,JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult Login(Person p)
        {
            ModelStateDictionary dt = new ModelStateDictionary();
            List<Errors> errors = new List<Errors>();
            bool isValied = true;
            if (ModelState["Email"].Errors.Count != 0) {
                isValied = false;
                List<string> ErrorLst = new List<string>();
                foreach (var item in ModelState["Email"].Errors)
                {
                    ErrorLst.Add(item.ErrorMessage);
                }
                errors.Add(new Errors
                {
                    Key = "Email",
                    ErrorLst = ErrorLst
                });
            }
            if (ModelState["Password"].Errors.Count != 0)
            {
                isValied = false;
                List<string> ErrorLst = new List<string>();
                foreach (var item in ModelState["Password"].Errors)
                {
                    ErrorLst.Add(item.ErrorMessage);
                }

                errors.Add(new Errors
                {
                    Key = "Password",
                    ErrorLst = ErrorLst
                });
            }

            return (isValied) ? Json("success", JsonRequestBehavior.AllowGet) :
                Json(errors, JsonRequestBehavior.AllowGet);
        }

    }

    public class Errors
    {
        public string Key { get; set; }
        public List<string> ErrorLst { get; set; }
    }

    public class Person : IValidatableObject
    {

        [Required(ErrorMessage = "please insert the first name")]
        [StringLength(0, ErrorMessage = "must be less than 5")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "please insert the last name")]
        public string LastName { get; set; }
        [Range(18, 44)]
        public int Age { get; set; }

        [Required(ErrorMessage = "email requred")]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",ErrorMessage ="invalied email address")]
        public string Email { get; set; }
        [Range(typeof(decimal), "0.00", "49.99")]
        public decimal Price { get; set; }

        [System.ComponentModel.DataAnnotations.Compare("Email", ErrorMessage = "email address must be same")]
        public string EmailConfirm { get; set; }

        [Required(ErrorMessage = "password requred")]
        public string Password { get; set; }

        [Required]
        [MaxWords(10, ErrorMessage = "what is fuking this")]
        public string MyError { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (LastName != null && LastName.Split(' ').Length > 10)
            {
                yield return new ValidationResult("The last name has too many words!",
                new[] { "LastName" });
            }
        }
    }

    // custom data anotation
    public class MaxWordsAttribute : ValidationAttribute
    {
        private readonly int _maxWords;
        public MaxWordsAttribute(int maxWords): base("{0} has too many words.")
        {
            _maxWords = maxWords;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                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 { getset; }
        public string Error { getset; }
    }
 
    public class IsValidate
    {
 
        public static bool IsValied(object x, out List<Errors> e)
        {
            ValidationContext context = new ValidationContext(x, nullnull);
            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 int Age { get; set; }
        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

CS Events