Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript return false or preventDefault is not working

I know this has to be something obvious, but even after following instructions elsewhere, I'm getting the same result.

The alert on the JavaScript call comes up, but after clicking okay, it continues to submit the form.

function validateBadEmail(inputText)
{
    var mailformat = /.ru$/
    if(inputText.value.match(mailformat))
    {
        alert("This is not an accepted email address");
        inputText.preventDefault();
    }
}

Here is how I'm calling it:

<input type="button" id="submit-btn" class="btn btn-blue btn-less-padding" name="submit-btn" value="<?= $txt_submit_btn; ?>" tabindex="0" onclick="return validateBadEmail(document.the_form.email)"/>

I have tried this by using return false instead of preventDefault but that's having the same effect.

If I change the onclick to onsubmit it doesn't even call the javascript at all.

Edit: clearly preventDefault is the wrong way, but if I try to do it this way, I'm still getting the same results

function validateBadEmail(inputText)
{
    var mailformat = /.ru$/
    if(inputText.value.match(mailformat))
    {
        alert("This is not an accepted email address");
        return false;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First: Your validateBadEmail function is missing a return instruction. Set one return value for either IF case.

EDIT

Second: Validating input data must be done in the onsubmit event handler of the containing FORM. Handling onclick events in the input controls won't prevent the form being sumbitted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...