-2

I am trying to validate my form but when function Ive created doesn't return false, it should stop submission process but it doesn't.

my code

var emailRE = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

function formChecker() {
    if (!emailRE.test(document.reservation.email.value)) {
        window.alert("Your e-mail address is invalid");
        return false;
    }

}

I'm getting the alert so function checks email but then stops at that point

Joe Doe
  • 193
  • 1
  • 5
  • 13
  • 3
    How are you calling it? – SLaks Jan 30 '14 at 19:29
  • 1
    How are you determining this? When you debug, is the `return` line ever reached? – David Jan 30 '14 at 19:29
  • Simply returning false will not stop submission in all browsers. Check this out: [return false not stopping form submit](http://stackoverflow.com/questions/12126583/return-false-not-stopping-form-submit) – Geeky Guy Jan 30 '14 at 19:31
  • 1
    @Renan: Wrong. The problem there is that he isn't actually returning false. (it's in a callback) – SLaks Jan 30 '14 at 19:33
  • Thats how Im calling it – Joe Doe Jan 30 '14 at 19:34
  • 1
    @JoeDoe Well, now *that* is wrong: `onsubmit="return formChecker()"` is the bare minimum change. Otherwise the result (whatever it is) of `formChecker` is discarded by the event callback. Otherwise, you can pass in the event object and use `returnValue(old IE)/preventDefault(everything else)`. – user2864740 Jan 30 '14 at 19:34
  • How exactly I should use preventDefault()? – Joe Doe Jan 30 '14 at 19:42
  • @SLaks I couldn't infer that from the question, sorry. – Geeky Guy Jan 30 '14 at 19:51

1 Answers1

0

First out:

I'm not sure that document.reservation.email.value will not always work across all browsers. Over the years, I have had my frustrations using that notation.

See: Best Practice: Access form elements by HTML id or name attribute?

The following example worked well for me. Posted a fiddle here:

<form id="reservation">
    Valid Email:    <input type=text id="validemail" value="abc@def.com">
    <label id=Result1>Result is: </label>
    <br>
    Invalid Email: <input type=text id="invalidemail" value="abc@def.">
    <label id=Result2>Result is: </label>
</form>

var emailRE = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

function formChecker(oElement) {
    if (!emailRE.test(oElement)) {
        window.alert("Your e-mail address is invalid");
        return false;
    } else {
        window.alert("Your e-mail address is valid");
        return true;
    }
}

document.getElementById("Result1").innerHTML = "Result is: " + formChecker(document.forms["reservation"].validemail.value);

document.getElementById("Result2").innerHTML = "Result is: " + formChecker(document.forms["reservation"].invalidemail.value);

See working example here: http://jsfiddle.net/vNmt4/1/

Community
  • 1
  • 1
Yossi
  • 331
  • 1
  • 3
  • 12