简体   繁体   English

如果陈述无效的JavaScript

[英]JavaScript if statment don't work

I need help with javascript. 我需要有关JavaScript的帮助。 here is my problem: 这是我的问题:

<script type="text/javascript">
    function validateForm() {
        var ime = document.getElementById('ime');
        var prezime = document.getElementById('prezime');
        var telefon = document.getElementById('telefon');
        var datum = document.getElementById('datum');
        var patt1 = /^\+[0-9]+$/;
        if (telefon.match(patt1) == null) {
            alert("Niste dobro uneli broj");

        }
        if (ime.value.length == 0 && prezime.value.length == 0 && telefon.value.length == 0 && datum.value.length == 0) {
            alert("Niste dobro uneli podatke!");
            return false;
        }

    }
</script>
<form action="popup.php" method="post" onsubmit="return validateForm()">Vase ime:
    <input type="text" name="ime" id="ime"> <br/>
    Vase prezime:
    <input type="text" name="prezime" id="prezime"> <br/>
    Broj telefona:
    <input type="text" name="telefon" id="telefon"> <br/>
    Datum rodjenja:
    <input type="text" name="datum" id="datum"> <br/>
    <input type="submit" name="save" value="sacuvaj">
</form>

I don't understand why telefon.match(patt1)==null) doesn't work. 我不明白为什么telefon.match(patt1)==null)无法正常工作。 Please help! 请帮忙!

Reason is because you can't apply regex to HTML Element, you can apply it to its value: 原因是因为您不能将正则表达式应用于HTML元素,可以将其应用于其值:

var telefon = document.getElementById('telefon').value;

Then you can execute your regex on var telefon 然后,您可以在var telefon上执行正则表达式

telefon is a DOM element, not a string telefon是DOM元素,而不是字符串

telefon.value can be matched 可以匹配telefon.value

The object stored in telefon will be a DOM element (eg HTMLDivElement ), which has no method "match". 存储在对象telefon将是一个DOM元素(例如HTMLDivElement ),它没有方法“匹配”。 You'll want to extract the pertinent text from that element before matching. 您需要在匹配之前从该元素中提取相关文本。 How you do that will depend on the exact DOM type: 如何执行将取决于确切的DOM类型:

if (telefon.value.match(patt1) == null) // For form elements...

if (telefon.innerHTML.match(patt1) == null) // For "plain" DOM elements...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM