Post Method Not giving Alerts like planned?

<form action="" method="post">
<div align="center"><legend>Add a Code</legend>
<label for="code"></label>
<input type="text" name="code" id="code" maxlength="10" />
<input type='button' 
 onclick=
             "isAlphanumeric(document.getElementById('code'),'Your Submission Contained Invalid Characters'); 
              isBadPhrase(document.getElementById('code'), 'Please Enter A Correct Friend Code!');"     
     value='Check Field' />

function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();   
    return false;
}

}

function isBadPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
    alert(helperMsg);
    elem.focus();
    return false;
}else{
    return true;
    }

}

What is wrong here?

Answers:

Answer

You aren't returning anything from your handler. You need to return a value (true/false) from the handler, especially if you want to stop the default. Note -- I'd also change the name of the "BadPhrase" method to "GoodPhrase" so that it matches the sense of the return value.

script:

function isAlphanumeric(elem, helperMsg){
    var alphaExp = /^[0-9a-zA-Z]+$/;
    if(elem.value.match(alphaExp)){
        return true;
    } else {
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

function isGoodPhrase(elem,helperMsg){
    var badPhrase=/EPW|ESW|\s/;
    if (elem.value.match(badPhrase)){
        alert(helperMsg);
        elem.focus();
        return false;
    } else {
        return true;
    }
}

function checkInput(id)    {
    return isAlphanumeric(document.getElementById(id),'Your Submission Contained Invalid Characters')
        && isGoodPhrase(document.getElementById(id), 'Please Enter A Correct Friend Code!');
}

html:

<input type='button' onclick="return checkInput('code');" value='Check Field' />

EDIT:

If you do the validation on form submit it will run regardless of how the form is submitted. You can add it as a onsubmit handler in the form tag, like you did for the click handler of the button. The button should probably be a submit button if it is supposed to trigger form submission.

Note: my preference would be to add the handlers via javascript rather than in the tag, but that's outside the scope of the question. I'd also probably use a framework rather than raw javascript, but that's also outside the scope.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.