SIGN UP MEMBER LOGIN:    
ARTICLE

Using the Confirm Attribute in MVC 3 Effectively

Posted by Vijay Prativadi Articles | ASP.NET MVC with C# November 10, 2011
This article mainly focuses on how to make sure that the properties within the particular class are matched and operations are performed well.
Reader Level:

This article mainly focuses on how to make sure that the properties within the particular class are matched and operations are performed well.  If it does not matches then it should fire off a validation to user stating that the data entered according to these properties does not match. So lets drill out and take a look how to implement it.


Let's take Student.cs with an extra property called ConfirmEmail. So This Property should match with the exsisting email property else should pop out an error to the user stating that the email entered is incorrect.

So the newly created property looks like this:

public string ConfirmEmail { getset; }

So let's add some attributes to this class where it should validate with exsisting Email Property

Besides that, we are also setting the datatype should be as an email type:

[DataType(DataType.EmailAddress)]

So, the complete code of student.cs looks like this

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MVC_Basic_Application.Models
{
    public class Student
    {
        [Key]

        public int StudentId { getset; }

        [Required(ErrorMessage = "Please Enter FirstName")]
        [StringLength(10, ErrorMessage = "FirstName morethan 10 charcs")]
        public string FirstName { getset; }

        [Required(ErrorMessage = "Please Enter LastName")]
        [StringLength(10, ErrorMessage = "LastName morethan 10 charcs")]
        public string LastName { getset; }

        [Range(5, 50, ErrorMessage = "Age Should Be Between 5 and 50")]
        public int Age { getset; }
        [Required(ErrorMessage = "Please Enter Location")]
        [StringLength(10, ErrorMessage = "Location morethan 10 charcs")]
        public string Location { getset; }

        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email appears to be invalid.")]
        [DataType(DataType.EmailAddress)]
        public string Email { getset; }

        [Required(ErrorMessage = "Confirm Email is required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                           ErrorMessage = "Email appears to be invalid.")]
        [DataType(DataType.EmailAddress)]
        [Compare("Email",ErrorMessage="Email Should Match")]
        public string ConfirmEmail { getset; }
    }
}



Let's also modify the StudentStateIntializer.cs . So Complete Code of StudentStateIntializer.cs looks like this:

StudentStateIntializer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace MVC_Basic_Application.Models
{
    public class StudentStateIntializer:DropCreateDatabaseIfModelChanges<StudentStateEntities>
    {
        protected override void Seed(StudentStateEntities context)
        {
            var stu = new List<Student>
            {
                new Student
                {
                    StudentId=1,
                    FirstName="Vijay",
                    LastName="Prativadi",
                    Location="Banglore",
                    Age=25,
                    Email="vijayprativadi@hotmail.com",
                    ConfirmEmail=
"vijayprativadi@hotmail.com"

                },
                 new Student
                {
                    StudentId=2,
                    FirstName="Uday",
                    LastName="Prativadi",
                    Location="Mumbai",
                    Age=28,
                    Email="uday@gmail.com",
                    ConfirmEmail="uday@gmail.com"
                }
            };
            stu.ForEach(d=>context.Students.Add(d));
        }
    }
}



We are almost done with major task now , So let's rebuild and run the application . So, the output of Index.cshtml looks like this:

one.jpg

The validations for the fields are shown if we do not enter data, where the screen looks like this:

Two.png

If we enter incorrect unmatched email the validation screen for this looks like this:


Three.png

If we enter incorrect email format the validation screen for this looks like this:

fourth.png
When are all good, no validations then screen looks like this:

Five.png
Finally, data added to database successfully which looks like this from our view screen :

Sixth.png

I hope this article is useful to you.

Thanks for reading this article....I look Forward for Comments and Feedback

 

Login to add your contents and source code to this article
share this article :
post comment
 

Thank You Dinesh!!!!!

Posted by Vijay Prativadi Nov 11, 2011

Good work Vijay, Welcome to the Mindcracker Community.

Posted by Dinesh Beniwal Nov 10, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor