Cuttlefish
Cuttlefish

Reputation: 187

Asp.Net Mvc 4: form validate on submit button click

I have a very simple newsletter subscription form :

    @using (Ajax.BeginForm("Register", "Home", new AjaxOptions
{
    Confirm = "confirm?",
    HttpMethod = "Post",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "response"
}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <div id="response">
        <div class="form-group">
            @Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "insert email" })
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <div class="form-group">
            <input type="submit" id="submit" value="subscribe" class="btn btn-default" />
        </div>
    </div>
}

The email field needs to be filled, and be a valid email. The problem is that as soon as I start typing inside the textbox, validation fires, and the message "email is invalid" pops out. This is quite annoying. Is there a way to fire validation when clicking on submit button, instead of every single textbox change? Thank you.

Upvotes: 0

Views: 3116

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

As an alternative a more straightforward way you can pass a function to the onfocusout and onkeyup settings of the jquery.validator to decide if an element has to be validated in those events or not, as this :

jQuery.validator.defaults.onfocusout = function (element, event) {
    // detectect if is the element you dont want validate
    // the element has to have the attribute 'data-control="mycitycontrol"'
    // you can also identify your element as you please
    if ($(element).data("control") === "mycitycontrol") return;
    if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
        this.element(element);
    }
}
jQuery.validator.defaults.onkeyup = function (element, event) {
    // detectect if is the element you dont want validate
    // the element has to have the attribute 'data-control="mycitycontrol"'
    // you can also identify your element as you please
    if ($(element).data("control") === "mycitycontrol") return;
    if (event.which === 9 && this.elementValue(element) === "") {
        return;
    } 
    else if (element.name in this.submitted || element === this.lastElement) {
        this.element(element);
    }
}

SOURCE

Upvotes: 1

Prasanth Jaya
Prasanth Jaya

Reputation: 4746

If you use ValidationMessageFor then the MVC will trigger immediately when you type. Instead use Jquery or javascript validation.

HTML:

@Html.TextBoxFor(model => model.Email, new { @class = "form-control", @placeholder = "insert email" })
<div id="emailerror" class="hide">The email is required</div>

JQuery:

var pattern = /^([\w\-\.]+)@@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,3}))$/;
        var email = $('#Email').val();
        if (email == "") {
            $('#emailerror').removeClass('hide');
            $('#emailerror').addClass('error');
            return false;
        } else if (!pattern.test(email)) {
            $('#emailerror').removeClass('hide');
            $('#emailerror').addClass('error');
            document.getElementById("emailerror").innerHTML = "The Email is not valid";
            return false;
        }
        else {
            $('#emailerror').addClass('hide');
            $('#emailerror').removeClass('error');
            return true;
        }

CSS:

.hide {
display:none;
}

.error {
position: absolute; 
margin-top:48px; 
margin-left:-300px;
z-index: 1060;
max-width: 276px;
padding: 10px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 13px;
font-weight: 400;
line-height: 1.42857143;
text-align: left;
white-space: normal;
color: #fff;
background-color: #c14a4a;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, .2);
border-radius: 0px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
box-shadow: 0 5px 10px rgba(0, 0, 0, .2);
}

Upvotes: 1

Related Questions