Computer Magic Logo
Custom validation

Sunday, November 22, 2015

Published by Aristotelis Pitaridis

There are cases that we want to make extra checks in order to make sure that the user typed what was supposed to type. For example we may need to check if the email typed by the user is not banned. In that case we have to write our own code to make this check. In order to implement it we will use the AddModelError member function of the ModelState object. Below we can see it implemented in our controller.

using ComputerMagic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Umbraco.Web.Mvc;

namespace ComputerMagic.Controllers
{
    public class ContactFormSurfaceController : SurfaceController
    {
        public ActionResult Index()
        {
            return PartialView("ContactForm", new ContactFormViewModel());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult HandleFormSubmit(ContactFormViewModel model)
        {
            if (model.EMail.Equals("pitaridis@hotmail.com"))
                ModelState.AddModelError("EMail", "Your email has been banned.");

            if (!ModelState.IsValid)
                return CurrentUmbracoPage();

            MailMessage message = new MailMessage();
            message.To.Add("EMAIL WHICH WILL RECEIVE THE MESSAGE");
            message.Subject = "New contact request";
            message.From = new MailAddress(model.EMail, model.Name);
            message.Body = model.Message;

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.Credentials = new System.Net.NetworkCredential("GMAIL ACCOUNT", "PASSWORD");
            smtp.EnableSsl = true;
            smtp.Send(message);

            TempData["success"] = true;

            return RedirectToCurrentUmbracoPage();
        }
    }
}

As we can see before we call the IsValid method of the ModelState object we check if the email typed by the user is equal to "pitaridis@hotmail.com" and if the result is true we add an error message to the model property EMail which contains the phrase "Your email has been banned.".