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..
RequiredAttribute) on your model (Registration) and framework will do it for you (with client side validation).