Validating form data in ASP.NET MVC

1

Is there any quicker and simpler way to validate a form's data in ASP.NET? so I do not have to be doing as many treatments as in the example below:

[HttpPost]
public ActionResult Attempt(string email, string password, Entities db)
{
    ViewBag.email = email;

    if (email == null || password == null || password.Length < 5)
    {
        TempData.Add("error", "E-mail ou senha inválidos.");
        return RedirectToRoute("Admin.Login");
    }

    var admin = db.admins.Where(p => p.email == email).FirstOrDefault();

    if (admin == null)
    {
        TempData.Add("error", "E-mail ou senha inválidos.");
        return RedirectToRoute("Admin.Login");
    }

    if(BCryptHelper.CheckPassword(password, admin.password))
    {
        FormsAuthentication.SetAuthCookie(email, false);
    }

    TempData.Add("error", "E-mail ou senha inválidos.");
    return RedirectToRoute("Admin.Login");
}

I'm looking for some more practical validation library, like this one in laravel, in php, for example:

$validator = Validator::make($request->all(), [
    'email'    => 'required|email|exists:users,email',
    'password' => 'required|min:5'
], [
    'required'  => trans('errors.required'),
    'min'       => trans('errors.min'),
    'email'     => trans('errors.email'),
    'exists'    => trans('notifications.login_failed'),
], [
    'email'     => trans('all.email'),
    'password'  => trans('all.password'),
]);

That already returns to the View all Validator errors, if there are:

if($validator->fails())
    return redirect()->route('login', $panel->handle)
        ->withInput($request->except('password'))->withErrors($validator);
    
asked by anonymous 02.03.2016 / 22:30

1 answer

3

Good afternoon has way but simple validation server side would be using data annotation it already has some properties ready but wanting you can customize I will put an example below.

using System.ComponentModel.DataAnnotations;

public class EadCapituloModel
{
    [Required(ErrorMessage = "Campo Capitulo é Obrigatorio")]
    [Display(Name = "Capitulo")]
    public string Capitulo { get; set; }
    [Required(ErrorMessage = "Campo tempo é obrigatório")]
    [Display(Name = "Tempo")]
    public string Tempo { get; set; }
    [Required(ErrorMessage = "Campo curso é obrigatório")]
    [Display(Name = "PlataformaId")]
    public int PlataformaId { get; set; }
    [Required]
    public int CursoId { get; set; }
    [Required(ErrorMessage = "Campo Nome do video obrigatório")]
    [Display(Name = "Video")]
    public string Video { get; set; }
    [Required(ErrorMessage = "Campo url é obrigatório")]
    [Display(Name = "URL")]
    [RegularExpression(@"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$", ErrorMessage = "Url não é válida")]
    public string URL { get; set; }
}

Following is a site that contains some explanations for each annotation: link

    
03.03.2016 / 17:20