1. 程式人生 > >JS實現簡單的判斷文字框長度

JS實現簡單的判斷文字框長度

有點點JS基礎的人都可以看得明白,那麼就不多說,直接上程式碼

JS程式碼如下

function chargeid() {
    var x, text;
    x=document.login.name.value;
    // 如果輸入的值 x 不是數字或者小於 1 或者大於 10,則提示錯誤 Not a Number or less than one or greater than 10
    if (x.length<4||x.length>9) {
        text = "使用者名稱長度應該為5-9之間"
        document.getElementById("charge1").innerHTML = text;
        return false;//阻止表單提交
    } else {
        text = "輸入正確";
        document.getElementById("charge1").innerHTML = text;
        return true;
    }
}

HTML程式碼(自動忽略屬性)

<div class="logo"></div>
<form name = "login" method="post" onSubmit= "return chargeid();">

    <div class="form-item">
        <input id="username" type="text" autocomplete="off" placeholder="使用者名稱" name = "name" required="required">
        <p class="tip" id="charge1"></p>
    </div>
    <div class="form-item">
        <input id="password" type="password" autocomplete="off" placeholder="登入密碼" name = "password" required="required">
        <p class="tip">密碼不正確</p>
    </div>

    <div class="form-item">
        <button type="submit" class="button1">登 錄</button>
    </div>
</form>