I followed scottgu's blog here and tried to do data validation. Succeeded. However what I see is that if my field is a required field, i get an error as soon as i loose focus from my textbox. I want validation to happen only when I click submit.
A:
that article is about using client side validation hence you get your form validated on client side. due to this, the form is validated by jquery when you loose the focus!
one way would be to use the server side validation.. i that case you will have a page refresh.
Update:
Here is the sample code.
Model:
public class GuestForm
{
[Required(ErrorMessage="Please enter your name")]
public string Name { get; set; }
[Required(ErrorMessage="Please enter your phone number")]
public string Phone { get; set; }
[Required(ErrorMessage="Please enter your email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your choice")]
public bool? YesNo { get; set; }
}
Form:
<div>
<% using(Html.BeginForm()) { %>
<%= Html.ValidationSummary() %>
Name: <%= Html.TextBoxFor(x => x.Name) %><br/>
Email: <%= Html.TextBoxFor(x => x.Email) %><br/>
Phone: <%= Html.TextBoxFor(x => x.Phone) %><br/>
Will you attend?
<%= Html.DropDownListFor(x => x.YesNo, new[] {
new SelectListItem { Text = "Yes",Value = bool.TrueString },
new SelectListItem { Text = "No",Value = bool.FalseString }
}, "Choose...") %><br/>
<input type="submit" value="Register!" />
<% } %>
</div>
Controller:
[HttpGet]
public ViewResult RegisterForm()
{
return View();
}
[HttpPost]
public ViewResult RegisterForm(GuestForm form)
{
if (ModelState.IsValid)
return View("Thanks", form);
else
return View();
}
this code will see that your form is validated on server side when user click submit. it will display the error message on top of the form in the form of list.
i hope this helps you.
Abdel Olakara
2010-09-04 10:42:13
I get that. But in a simple web page scenario too, unless you click the submit button the validation does not happen. I want my users to see a consolidation list of errors and then act accordingly. Seeing an error after each lost focus may reduce user interaction.
Ashish
2010-09-04 10:51:54
@Ted, that is possible.. i will submit another answer with example code as pasting code in comment can make it unreadable.
Abdel Olakara
2010-09-04 11:07:27
@Ted,check the updated answer
Abdel Olakara
2010-09-04 11:22:42
@Abdel, Thanks and appreciate for your reply. However my question was whether I can validate my form on client side only after clicking submit. I think I need to use jQuery validation instead of MVC validation for that. Thoughts?
Ashish
2010-09-04 15:37:52