简体   繁体   English

如何使用 Javascript 验证表单字段

[英]How To Validate Form Field Using Javascript

I am trying to validate my form phone field to prevent users from entering the same numbers in my javascript.我正在尝试验证我的表单电话字段以防止用户在我的 javascript 中输入相同的号码。

If the number provided by the user matches with the same numbers in my javascript, They will get a warning and the form would not submit.如果用户提供的号码与我的 javascript 中的相同号码匹配,他们将收到警告并且表单不会提交。

However, I noticed that my code below shows the warning whether the numbers match or not.但是,我注意到我的下面的代码显示了数字是否匹配的警告。

I need corrections to know what I am doing wrong.我需要更正才能知道我做错了什么。 Thanks.谢谢。

Code below;下面的代码;

 $('.validate').hide(); $('body').on('blur', '#phone', function() { $('.validate').hide(); isphone($(this).val()); }); function isphone(phone) { if (phone === "1234" || phone === "23456"){ $(".validate").show(); } else { $(".validate").hide(); } }
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <form action='' method='POST' id="submitForm" > <input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/> <div class="validate"><span style="color: red;"><b>Please enter a valid phone!</b></span></div> <button href='/' type='submit' id="submitForm">Process</button> </form>

I believe this should work.我相信这应该有效。 I move the changes for hiding and showing $('.validate') to the isphone function, and removed that done variable that wasn't doing anything useful (used if...else instead).我将隐藏和显示$('.validate')的更改移动到isphone function,并删除了没有做任何有用的done变量(改为使用if...else )。 Also, don't use document.getElementById if you're already using JQuery.另外,如果您已经在使用 JQuery,请不要使用document.getElementById

    $('.validate').hide();
    $('body').on('blur', '#phone', function() {
        $('.validate').hide();
        isphone($(this).val());
    });

    function isphone(phone) {
        if (phone === "1234" || phone === "23456"){
            $(".validate").hide();
        } else {
            $(".validate").show();
        }
    }

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

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