简体   繁体   中英

How can I stop a form submit and validate with javascript?

I've come across a form that looks like this that I cannot change:

<form id="mx_locator" name="mx_locator" method="post" action="search-results">

  <!-- form elements -->
  <span><input type="image" src="/images/search.png" onclick="loader()"></span>

</form>

It's inside of a CMS that knows to forward the form data and produce a results page when clicked. The loader function call just handles adding/removing a class for some effect.

I've been asked to write a javascript that validates the form. There is a zip code field and a city field. One or the other has to be filled out. Not both, but one or the other. So when someone clicks that button my javascript has to stop the submit, check those fields, and only go forward if they're good.

In short, how would I go about doing this? More than anything, I'm worried the form will process no matter what the js does, because the CMS is controlling it. I can't change the form html at all. I can just add the JS.

Start by adding the onsubmit attribute to the form tag.

<form id="mx_locator" onsubmit="return ziporcity(this)" name="mx_locator" ...

Then add a script tag to your document either containing or linking to the function ziporcity, which you can write like this:

<script>
function ziporcity(f) { return /\d{5}/.test(f['zipFieldName'].value) || /\S/.test(f['cityFieldName'].value); }
</script>

This simple validation function checks that one or the other or both are true, that the zip field contains 5 consecutive digits (9 digits would also pass), and/or the city field contains non-whitespace.

You need to change zipFieldName to be the name contained in the name="..." attribute of the zip field in your form, and the cityFieldName to be the name of the city field.

<script> 
$(document).ready(function() {
    $("#mx_locator").submit(function() {  
      var isValid = callSomeValidationFunctionThatReturnTrueFalse();
      return isValid;  // the key is return false will prevent submit
    });
});
</script>

You will need to include jQuery. If something is really weird where your form submit event is being completely overrun by the CMS, then just hide and create a new form in it's place.

<script> 
$(document).ready(function() {
    // save old form html and hide
    var myForm = $("#mx_locator");
    var formHtml = myForm.html();
    myForm.html("").hide();

    // append new form in its place and 
    var myNewForm = $('<form id="mx_locator2" name="mx_locator2" .../></form>');
    myNewForm.html(formHtml);
    myNewForm.insertAfter(myForm);
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM