文本框验证数字的长度

时间:2013-08-21 10:28:44

标签: jquery validation html-validation

以下是我的观看页面,

<table class="width_full cellspace" border="0" cellspacing="0" cellpadding="0" style="vertical-align:top">
    <tr>
        <td colspan="3">
            <strong>@Html.Label(Model.objTRSkillGradeLabelEntities.lblBPBlockedfor)</strong>
        </td>
    </tr>
    <tr style="font:11px/20px Arial, Helvetica, sans-serif">
        <td style="width: 33%;">
            AccountId
            <span class="redFont">*</span> :
            <input type="text" id="txtBlkAccountId" />
            <label id="lblAccountId" class="error"> </label>
        </td>
    </tr>
    <tr>
        <td colspan="3" class="textCenter">
            <input class="btnInput" type="submit" value=@Model.objTRSkillGradeLabelEntities.btnBPSubmit onclick="javascript:UpdateTRData();" />
        </td>
    </tr>
</table>
function UpdateTRData() {  
    var errorflag;
    document.getElementById('lblAccountId').innerText = "";

    var BlkAccountIdV = $('#txtBlkAccountId').val();
    if (BlkAccountIdV == "" || BlkAccountIdV == null) {            
        document.getElementById('lblAccountId').innerText = "Enter AccountID";
        errorflag=1;
    } 

    var txtLength = $("#txtBlkAccountId").val().length;
    if (txtLength != 7) {
        document.getElementById('lblAccountId').innerText = "Enter valid AccountID";
        errorflag = 1;
    }

    var i;
    s = txtLength.toString();
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (isNaN(c)) {
            document.getElementById('lblAccountId').innerText = "Enter valid AccountID";
            errorflag = 1;
        }
    }

    if (errorflag == 1) {
        return false;
    }

    var AssociateID = $('#lblAssoID').text();       
    var BlkAccountId = $('#txtBlkAccountId').val();

    $.ajax({                      
        url:"@Url.Action("UpdateBlockDetails", "TravelReady")",             
        data:{            
            strAssociateID: AssociateID,           
            strBlkAccountId: BlkAccountId
        },
        dataType: "json",
        type: "POST",
        error: function(e) {
            alert(e.getException().getMessage());
            alert("An error occurred.");
        },
        success: function(data) { return data; }
    });
}

我已验证帐户ID文本框仅接受7位数字。单击按钮后,此验证将起作用。我需要再提供一个验证,例如,输入超过20个数字。那就是如果我输入第21位警告框应该显示。如何使用jQuery执行此验证?

2 个答案:

答案 0 :(得分:2)

您可以使用文本框maxlength属性。

<input type="text" name="txtBlkAccountId" maxlength="20">

OR

你可以使用JS:

$("#txtBlkAccountId").on('keypress',function(){   
    if($(this).val().length>20){
        alert("error message");
        return false;
       }
});

<强> DEMO

答案 1 :(得分:2)

你可以使用

 <input type="text" id="txtBlkAccountId"  maxlength="20" />
相关问题