简体   繁体   中英

Validating a field before submitting

I have a text field and a button.

I want to validate the field, and if the validation fails, the button should not "submit".

This is my button:

<input type="submit"  onsubmit="return validate()"

And this is my validation function:

function validate()
{
    var number = document.getElementById("temp");
    alert (number.value);

    if ( /^[0-9]{12}$/.test(number.value) ) 
    { 
        alert(number);
        return true;
    }
    alert ("מספר הפנייה חייב להיות בן 12 ספרות");
    return false; 
}

But it wont work, the submit occures any way.

Any ideas?

应将onsubmit事件附加到form对象,而不是提交按钮。

It should be like this:

<form id = "myform" onsubmit="return validate()" action = "mypage.php">


<input type="submit">

</form>

This should work...

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