Johhan Santana
Johhan Santana

Reputation: 2425

Verify if input textbox is empty or null c#

I'm trying to make a registration form which returns an error message if the user didn't fill up all the textbox inputs.

What I have for now is

@using (Html.BeginForm("Register", "Main", FormMethod.Post))
{
@Html.TextBoxFor(r => r.FirstName)
@Html.TextBoxFor(r => r.LastName)
@Html.PasswordFor(r => r.Password)
@Html.PasswordFor(r => r.Password2)
@Html.TextBoxFor(r => r.Email)
@Html.TextBoxFor(r => r.Phone)
<input type="submit" value="Continue"/>
}

those are the fields that I want to check if they are null or empty

In my controller I have done an if statement to check if the email has already been used and it returns an error message but I wouldn't like to make an if statement for every field, that doesn't sound right.

[HttpPost]
    public ActionResult Register(Registration signingUp)
    {


        var db = new SolutiondbEntities();

        var FindEmail = db.tblProfiles.FirstOrDefault(e => e.PROF_Email == signingUp.Email);

        if (FindEmail == null)
        {
            var Data = db.tblProfiles.Create();

            Data.PROF_FirstName = signingUp.FirstName;
            Data.PROF_LastName = signingUp.LastName;
            Data.PROF_Password = signingUp.Password;
            Data.PROF_Email = signingUp.Email;
            Data.PROF_CellNum = signingUp.Phone;

            db.tblProfiles.Add(Data);

            int Saved = db.SaveChanges();

            if (Saved != 0)
            {
                Response.Write("Saved");
            }
            else
            {
                Response.Write("Something went wrong!");
            }

        }
        else
        {
            Response.Write("Theres already an user with that Email");
        }


        return View();
    }

I would like to know how to check each field on the form for a null so I can return an error telling the user to fill all the blanks or fields.

Thanks!

EDIT:

Here's what I have in my model

public class Registration
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [DataType(DataType.Password)]
    public string Password { get; set; }
    public string Password2 { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

EDIT2:

I've added this lines of codes and it seems to work but not accurate as it will continue with the registration if any of the fields are not empty

foreach (string key in Request.Form.Keys)
        {
            if (Request.Form[key] == "")
            {
                Response.Write("Please, fill in all the fields");
            }
            else
            {
                Response.Write("Thanks for registering.");
            }
            return View();
        }

this works if I don't put anything in any of the fields, as soon as I put anything (even a space) it will continue..

Upvotes: 1

Views: 10263

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67148

You can do it all with Data Annotations. First of all, I'd like to remind you that validation must be done on both the server-side and client-side. If you do it only on the server then you'll have a post just to know model errors (and this will consume time and bandwidth). If you do it only on the client then you'll be open to malicious posts or you won't detect validation error because JavaScript is disabled.

How to do it? Let's first pick your model and add proper annotations:

public class Registration
{
    [Required] public string FirstName { get; set; }
    [Required] public string LastName { get; set; }
    [DataType(DataType.Password), Required] public string Password { get; set; }
    [Required] public string Password2 { get; set; }
    [Required] public string Email { get; set; }
    [Required] public string Phone { get; set; }
}

Please note you may/should add all possible validations (password matching, e-mail, and phone number regex). Using proper annotations (see first link) will allow you to have better validation rules (for example FirstName must be at least two non-whitespace characters, the e-mail must be a valid address, and so on). Let's see a quick example (let's check MSDN about individual attributes for more details and a better usage):

public class Registration
{
    [Required, MinLength(2)]
    public string FirstName { get; set; }
    
    [Required, MinLength(2)]
    public string LastName { get; set; }
    
    [DataType(DataType.Password), Required]
    public string Password { get; set; }
    
    [Required, Compare("Password")]
    public string Password2 { get; set; }
    
    [Required, EMailAddress]
    public string Email { get; set; }
    
    [Required, Phone]
    public string Phone { get; set; }
}

If you did enable unobtrusive JavaScript (and required HTML code) then it's all you need for client-side validation.

Server-side is even easier because the model binder will do everything for you, you just need to check if the model is valid or not:

[HttpPost]
public ActionResult Register(Registration signingUp)
{
    if (!ModelState.IsValid)
        return View(signingUp);

    // Model is valid, work with it... 
}

Note that you're not (strictly) required to check if the model is valid or not, if you have the same constraint in your database then it'll throw an exception when trying to insert a new record. The user will get back a not so meaningful (from his perspective) error message so I suggest always do this check.

Upvotes: 3

Related Questions