javascript单元格数验证 [英] javascript cell number validation

查看:99
本文介绍了javascript单元格数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JavaScript 验证单元格编号。

I want to validate cell number using JavaScript.

这是我的代码。

if(number.value == "") {
    window.alert("Error: Cell number must not be null.");
    number.focus();
    return false;
}

if(number.length != 10) {
    window.alert("Phone number must be 10 digits.");
    number.focus();
    return false;
}

这是问题,当我提交表格时没有输入电话号码,它显示错误单元格编号不能为空。它工作正常。

Here is the issue, when I submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.

当我提交小区号码小于10位的表格时,显示的电话号码必须是10位数。它也没关系。

When I submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. It is also fine.

问题是当我提交10位数的表格时,它也显示错误电话号码必须是10位数。

The problem is when I submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.

请帮帮我。
谢谢。

Please help me. Thank You.

并且还需要仅针对单元格数字的验证码。

And also need the validation code for only digits for cell number.

推荐答案

如果 number 是你的表单元素,那么它的长度将是 undefined 因为元素没有长度。你想要

If number is your form element, then its length will be undefined since elements don't have length. You want

if (number.value.length != 10) { ... }

但是,一次性完成所有验证的更简单方法是使用正则表达式:

An easier way to do all the validation at once, though, would be with a regex:

var val = number.value
if (/^\d{10}$/.test(val)) {
    // value is ok, use it
} else {
    alert("Invalid number; must be ten digits")
    number.focus()
    return false
}

\d 表示数字和 {10} 表示十次。 ^ $ 将其锚定到开头和结尾,所以类似 asdf1234567890asdf 不匹配。

\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.

这篇关于javascript单元格数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆