ASP MVC : The validation method is not working !

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • arao
    New Member
    • Apr 2010
    • 1

    ASP MVC : The validation method is not working !

    In URL ASP.NET/LEARN/MVC/Tutorial-28-cs.aspx

    The code compiles, but at run time I get NULL Reference in FirstName .

    The code is as follows:


    Code:
    protected void ValidateContact(Contact contactToValidate)
            {
                if (contactToValidate.FirstName.Trim().Length == 0)
                    ModelState.AddModelError("FirstName", "First name is required.");
                if (contactToValidate.LastName.Trim().Length == 0)
                    ModelState.AddModelError("LastName", "Last name is required.");
                if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
                    ModelState.AddModelError("Phone", "Invalid phone number.");
                if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
                    ModelState.AddModelError("Email", "Invalid email address.");
            }
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    If you pass in a Contact object with none of the values set then yeah, they are null.

    Code:
    contactToValidate.FirstName.Trim().Length
    You can't Trim() or get the length of a null.
    You need to check if your object is null before trying to perform actions on it.
    You should also make sure that your default constructor for the Contact object assigns actual values to variables.

    Originally posted by OriginalPoster
    "How do I fix a 'object reference not set to an instance of an object' error?
    The line your code stopped on while debugging holds all your answers.
    One of the variables/objects was created but not initialized. For example:
    Code:
    string TempString;// Created but not initialized so this is still null
    //versus
    string TempString = string.empty;
    Debug your project again. This time, when it breaks on a line look at the Locals pallet to see which variable/object is null. You can also hover your mouse over each variable and the hothelp will shows its value. One of them will be null.

    Comment

    Working...