Post Method Not giving Alerts like planned?

后端 未结 1 341
轮回少年
轮回少年 2021-01-28 14:25
Add a Code
1条回答
  •  悲哀的现实
    2021-01-28 15:03

    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:

    
    

    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.

    0 讨论(0)
提交回复
热议问题