簡體   English   中英

驗證表單JavaScript

[英]validate form JavaScript

我正在嘗試驗證表單中的某些字段。

我想檢查他們是否輸入了所需字段的正確區號。

區號應的一個212313 ,或414

這是家庭作業,所以我不能使用正則表達式,我不是真的要求答案,但這是我正在嘗試使用但不是他們真的為我工作

if (input.substr(0,2) != 212|| input.substr(0,2) != 313 || input.substr(0,2) != 414)
                Message += " <p>Sorry but you have enter wrong area code!!!</p>";

我已經嘗試過使用substring indexOf但實際上我並不知道在這種情況下它們是非常正確的。

無論如何要驗證,但不是正則表達式?

謝謝

嘗試這個

if (input.substr(0,3) != 212|| input.substr(0,3) != 313 || input.substr(0,3) != 414)
      Message += " <p>Sorry but you have enter wrong area code!!!</p>";

我沒有測試它

<input type="text" id="num"/>
<div id="msg"></div>

// This should run in a window.onload or $(document).ready() block
var num = document.getElementById('num'),
    msg = document.getElementById('msg');

num.onblur = function(){
    var areacodes = '212|313|414|',
        areacode = this.value.replace(/[^0-9]/, '').substring(0,3),
        message = 'Area code validates.';

    if (areacode.length < 3 || areacodes.indexOf(areacode + '|') === -1) {
        message = "Sorry but you have entered an invalid area code.";
    }

    msg.innerHTML = message;
};

http://jsfiddle.net/userdude/gfJWX/1

input我猜是一個string變量,而不是指向input元素的DOM注釋。

這不應該工作嗎?

var str = input.trim().substr(0,3);
if ( !{212:1, 313:1, 414:1}[ str ] ){
    Message += " <p>Sorry but you have enter wrong area code!!!</p>";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM