简体   繁体   中英

JavaScript validation - document.getElementById not working in Bootstrap modal

I am using an onSubmit() function to validate form entries.

The form and validation function work OK,if the form is in a standalone php file or an html file.

But when the form is embedded in a Bootstrap modal the JS validation function throws an error message. [object HTMLInputElement]

I have tried changing document.getElementById('uemail') to document.getElementById('uemail').value as recommended in another answer, but no value has apparently been passed to the function.

If I remove the onSubmit() attribute then the values are passed correctly to the action script on the server.

This must be common usage. What am I doing wrong?

This is an abbreviated section of my code:

<script>
function formCheck() {
    var valid = true;
    //alert('in function');
    var email = document.getElementById('uemail');
    alert('email:' + email);
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email)) {
        alert('Please provide a valid email address');
        email.focus;
        valid = false;
    }
    return valid;
}
</script>


<form id="regform" action="action.php" method="post" onSubmit="return formCheck()">
    Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id ="ast">*</span><br>
    <input type="submit" name="Submit" value="Register" />
</form>

EDIT: looks like you can't do document.getElementById , you can do this instead:

function formCheck(formEl) {
    //...
    var email = formEl.getElementsByTagName("input")[0].value;
    // this will get the first input-element in your form

and

onsubmit="return formCheck(this)"

Mistake: The variable email you are testing is a HTMLElement, not a string:

在此处输入图片说明

Solution: set email to the value of the HTMLInputElement:

var email = document.getElementById('uemail').value;

also email.focus; is not doing anything, use email.focus();

Demo:

 function formCheck() { var valid = true; //alert('in function'); var email = document.getElementById('uemail').value; alert('email:' + email); var filter = /^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email)) { alert('Please provide a valid email address'); email.focus; valid = false; } return valid; } 
 <form id="regform" action="action.php" method="post" onsubmit="alert(formCheck())"> Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id="ast">*</span> <br> <input type="submit" name="Submit" value="Register" /> </form> 

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