用于验证的HTML代码

时间:2013-12-26 05:52:46

标签: javascript html

用于验证姓名,手机号码等的HTML代码,方法是在红色文本框旁边显示错误消息

if(p.length!=10)  region.innerHTML="phone num must be 10 digits";
if(isNaN(p))   region.innerHTML="digits only";

我使用过这种格式但没有用。

2 个答案:

答案 0 :(得分:1)

if you want to use html validation try this once:

        <style type="text/css">
            .validationError {
                border: solid 2px red;
            }
            .validationValid {
                border:  solid 2px green;
            }
        </style>

    <form id="customerForm">
        <label>
            First Name:
            <input id="firstName" required />
        </label>
        <label>
            Social Security Number:
            <input id="ssn" required pattern="^[0-9]{3}-[0-9]{2}-[0-9]{4}$" title="Expected pattern is ###-##-####" />
        </label>
        <input type="submit" />
    </form>

script:


<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery.h5validate.js"></script>
<script type="text/javascript">

    // Enable h5Validate plugin
    $("#customerForm").h5Validate({
        errorClass: "validationError",
        validClass: "validationValid"
    });

    // Prevent form submission when errors
    $("#customerForm").submit(function (evt) {
        if ($("#customerForm").h5Validate("allValid") === false) {
            evt.preventDefault();
        }
    });

</script>

答案 1 :(得分:0)

尝试以下功能

var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
 region.innerHTML = phoneNumber + ' contains 10 digits';
}
else {
 region.innerHTML= phoneNumber +' does not contain 10 digits';
}