0

I have a field called ACTIVITY_NAME which I have defined as such:

[Required(AllowEmptyStrings = false, ErrorMessage = "Acitivity Name is Required.")]
[StringLength(255)]
    public string ACTIVITY_NAME { get; set; }

I setup my textbox to render it front-end like this:

@Html.TextBoxFor(m => m.EditActivity.ACTIVITY_NAME, new { @id = "ActivityName", @class = "width400", placeholder = Localization.ActivityName })
@Html.ValidationMessageFor(m => m.EditActivity.ACTIVITY_NAME)

When the form is submited, the following JS handler is fired:

    $('#AddTaskActivity').click(function (evt) {
        $('#activityModal').modal('hide');
        evt.preventDefault();
        var formData = $('#ActivityForm').serialize();
        CreateActivity(formData);
    });

So basically, this would prevent the default handler, and the validation would not fire. I didn't write this code, but I would like to add validation. How do I force fire the validation in the handler before it post to server?

6
  • You have to do a fake submit form for validation triggers. Commented Jun 23, 2016 at 18:48
  • I can't just call the validation client side? Commented Jun 23, 2016 at 18:54
  • Client side validation will activate only when you try to submit the form. Commented Jun 23, 2016 at 18:56
  • Right, and I would like force that validation before submitting. Commented Jun 23, 2016 at 18:57
  • Are you submitting the form via Ajax? Commented Jun 23, 2016 at 18:58

1 Answer 1

1

There might be a better way, but this is how I trigger client side validation before submitting the form. They must be called before submitting the form.

// For non Ajax forms
function ValidateHtml5(event) {
    event = event || window.event || event.srcElement;

    var form = $(event.target);

    if (form[0].checkValidity()) {
        return true;
    } else {
        event.preventDefault();
        $('<input type="submit">').hide().appendTo(form[0]).click().remove(); // trigger
        return false;
    }
}

// For Ajax form validation
function ValidateHtml5Ajax(form) {
    if (form.checkValidity()) {
        return true;
    } else {
        $('<input type="submit">').hide().appendTo(form).click().remove(); // trigger
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.