Javascript 电话号码验证器

Javascript 电话号码验证器,javascript,html,regex,validation,Javascript,Html,Regex,Validation,我有一个验证电话号码的代码: function phvalid() { var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; if (regexObj.test(subjectString)) { var formattedPhoneNumber = subjectString.replace(regexObj, "($1) $2-$3"); } else {

我有一个验证电话号码的代码:

function phvalid() {
    var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (regexObj.test(subjectString)) {
        var formattedPhoneNumber = subjectString.replace(regexObj, "($1) $2-$3");
    } else {
        alert("Invalid Number");
    }
}
我正在尝试将其验证到以下html代码的主体中:

<p class="normal">Phone:
    <input type='text' id='ph' />
    <input type='button' onclick="phvalid();" value="Click" />
</p>
电话:


这个函数是对的还是我做错了什么?

您从未定义过
subjectString

试试这个:

这将运行您的函数,但我不确定您使用
formattedPhoneNumber
块的目的是什么

此外,您还需要确保onclick可以访问此文件。因此,您必须将js放在身体内或加载dom后运行的块内

编辑:我相信这就是您想要的
格式电话号码

Edit2:对于下面评论中的新要求。。。试试这个:


实际上,由于在本例中,
regexObj
没有被用于验证,您可以简单地将其作为
/(\d{3})(\d{3})(\d{4})/

来定义
subjectString

试试这个:

这将运行您的函数,但我不确定您使用
formattedPhoneNumber
块的目的是什么

此外,您还需要确保onclick可以访问此文件。因此,您必须将js放在身体内或加载dom后运行的块内

编辑:我相信这就是您想要的
格式电话号码

Edit2:对于下面评论中的新要求。。。试试这个:


实际上,由于在本例中,
regexObj
没有用于验证,您可以将其作为
/(\d{3})(\d{3})(\d{4})/

查看非常通用的电话号码传真号码验证代码-希望它会有用

公共空位电话机 (FacesContext FacesContext, UIComponent UIComponent, 对象(对象){

字符串msg2=”“;
if(对象!=null){
字符串phnNo=object.toString();
int-openB=0;
int closeB=0;
布尔闭合fg=false;
char[]xx=phnNo.toCharArray();
用于(字符c:xx){
如果(c=='('){
openB=openB+1;
}如果(c=='),则为else){
closeB=closeB+1;
}
如果(关闭B>打开B){
closeFg=true;//在任何给定时间,闭括号将不会大于开括号。
}
}
//如果openB=0,则闭合括号和开口括号的数量等于| |开口括号必须始终位于闭合括号之前
//关闭括号不得出现在第一次出现打开括号之前
if(openB!=closeB | | closeFg==true | |(phnNo.lastIndexOf(“(”)>phnNo.lastIndexOf(“)”)||
(phnNo.indexOf(“”)”+phnNo.lastIndexOf(“+”));
系统输出println(“括号索引-->”+phnNo.charAt(0));
if(matcher.matches()){
if(phnNo.contains(“+”)| | phnNo.contains(“-”){
抛出新的ValidatorException(新的FacesMessage)(FacesMessage.SEVERITY_错误,错误,
“不能包含两个连字符(-)或加号(++)”);
}else if(phnNo.lastIndexOf(“+”)大于1){
抛出新的ValidatorException(新的FacesMessage)(FacesMessage.SEVERITY_错误,错误,
“加号应在适当的位置”);
}else如果(phnNo.lastIndexOf(“+”)==1&&phnNo.charAt(0)!='(')){
抛出新的ValidatorException(新的FacesMessage)(FacesMessage.SEVERITY_错误,错误,
“加号应在适当的位置”);
}else if(phnNo.startsWith(“”)| | phnNo.endsWith(“”){
抛出新的ValidatorException(新的FacesMessage)(FacesMessage.SEVERITY_错误,错误,
“开始和结束时不允许有空格”);
}
}否则{
抛出新的ValidatorException(新的FacesMessage)(FacesMessage.SEVERITY_错误,错误,
“仅允许数字字符,+,()和-”);
}
}
}

查看非常通用的电话号码传真号码验证代码-希望它会有用

公共空位电话机 (FacesContext FacesContext, UIComponent UIComponent, 对象(对象){

字符串msg2=”“;
if(对象!=null){
字符串phnNo=object.toString();
int-openB=0;
int closeB=0;
布尔闭合fg=false;
char[]xx=phnNo.toCharArr
function phvalid() {

    var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    var subjectString = document.getElementById("ph").value;
    if (regexObj.test(subjectString))

    {
        var formattedPhoneNumber = subjectString.replace(regexObj, "($1) $2-$3");
    } else {
        alert("Invalid Number");
    }

}
function phvalid() {
    var subjectString = document.getElementById("ph").value;
    subjectString = subjectString.replace(/[^\d]/g, "");
    if (subjectString.length == 10) {
        var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
        var formattedPhoneNumber = subjectString.replace(regexObj, "($1) $2-$3");
        document.getElementById("ph").value = formattedPhoneNumber;
    } else {
        alert("Invalid Number");
    }
}
    String msg2 = "";
    if (object != null) {
        String phnNo = object.toString();
        int openB = 0;
        int closeB = 0;
        boolean closeFg = false;
        char[] xx = phnNo.toCharArray();
        for (char c : xx) {
            if (c == '(') {
                openB = openB + 1;
            } else if (c == ')') {
                closeB = closeB + 1;
            }

            if (closeB > openB) {
                closeFg = true; //closed brackets will not be more than open brackets at any given time.
            }
        }
        //if openB=0 then no. of closing and opening brackets equal || opening bracket must always come before closing brackets
        //closing brackets must not come before first occurrence of openning bracket
        if (openB != closeB || closeFg == true || (phnNo.lastIndexOf("(") > phnNo.lastIndexOf(")")) ||
            (phnNo.indexOf(")") < phnNo.indexOf("("))) {
            msg2 = "Brackets not closed properly.";
            FacesMessage message2 = new FacesMessage(msg2);
            message2.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message2);
        }
        if (phnNo.contains("()")) {
            msg2 = "Empty Brackets are not allowed.";
            FacesMessage message2 = new FacesMessage(msg2);
            message2.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message2);
        }
        if (phnNo.contains("(.") || phnNo.contains("(-") || phnNo.contains("-)")) {
            msg2 = "Invalid Phone Number.Check content inside brackets.";
            FacesMessage message2 = new FacesMessage(msg2);
            message2.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ValidatorException(message2);
        }

        openB = 0;
        closeB = 0;
        closeFg = false;
        //check for valid language name.Allowed- brackets,dots,hyphen

        String expression = "([0-9\\-\\+\\(\\)]+)";
        CharSequence inputStr = phnNo;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        String error = "Invalid Phone Number";
        System.out.println("Index of plus is--->" + phnNo.lastIndexOf("+"));
        System.out.println("Bracket index--->" + phnNo.charAt(0));

        if (matcher.matches()) {
            if (phnNo.contains("++") || phnNo.contains("--")) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                              "Can not contain two hyphen(--) or plus(++)"));
            } else if (phnNo.lastIndexOf("+") > 1) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                              "Plus sign should be in proper place"));
            } else if (phnNo.lastIndexOf("+") == 1 && phnNo.charAt(0) != '(') {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                              "Plus sign should be in proper place"));
            } else if (phnNo.startsWith(" ") || phnNo.endsWith(" ")) {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                              "Space Not allowed at start and end"));
            }

        } else {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, error,
                                                          "Only numeric character,+,() and - allowed"));
        }

    }
}