Html.BeginForm using onSubmit to validate
Is this a correct summary?
On submit you want to validate your form with your jQuery function. If validation is passed then you want the submit to be continued, otherwise you want the submit to be canceled.
If my summary isn't correct, then please clarify your question a bit more.
If I summed it up accurately, you can change your jQuery function to:
$(function validateForm(event) {
event = event || window.event || event.srcElement;
var initialMonoReading = $('#InitialMonoReading').val();
var newMonoReading = $('#newMonoReading').val()
if (~~newMonoReading < ~~initialMonoReading) {
$('#MonoErrorMessage').text("New Mono Readings must be MORE than existing");
$('#MonoErrorMessage').show();
event.preventDefault();
}
else {
$('#MonoErrorMessage').hide();
}
});
And while creating markup, use following line:
@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))
This is what worked for me,
@using (Html.BeginForm("Tag", "Translations", FormMethod.Get, new { enctype = "multipart/form-data", onsubmit = "return validateTagInput()" }))
JQuery,
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function validateTagInput()
{
//do validation
if (x,y,z)
{
return true; //let page be submitted
}
else {
return false; //do not let submission go through
}
}
</script>
This worked for me
function validateForm() {
if ($('#newMonoReading').val() == 'bla bla bla') {
alert('bla bla bla');
return false;
}
else {
form1.submit();
}
@using (Html.BeginForm("action", "controller", FormMethod.Post, new { @id = "form1"}))
{
<input type="text" id="newMonoReading"><br>
<input type="submit" value="Submit" onclick = "return validateForm();" class="btn btn-primary">
}