协助用JavaScript编写Regex进行电话号码验证

时间:2016-08-16 19:34:13

标签: javascript regex

我的任务是为JavaScript正则表达式电话验证检查器编写if/else结构,我遇到了问题。我的约束和格式如下:

  • 仅接受数字(最小4到最大40)
  • 4位电话分机,用于分机,格式为“ext ####”
  • 10位数的电话号码,将通过替换为“(###)### - ####”
  • 进行格式化
  • 11位数的电话号码,将通过替换为“(###)### - ####”
  • 进行格式化
  • 14或15位电话号码,将通过替换为“(###)### - #### ext ####”
  • 进行格式化

我试图去除除数字之外的所有字符,然后通过正则表达式处理它。当我将x = x.replace(/[^\d]+/g, '');移到if (x.length == 4) {之上且var x = newValue;以下时,它无效。

到目前为止我所做的工作如下:

function onChange(control, oldValue, newValue, isLoading) {
    // If the newValue is empty, return
    if (isLoading || newValue === '') {
        return;
    }
    // If the newValue is the same as the oldValue, return
    if (newValue == oldValue) {
        return;
    }

    // If the newValue is a completely new value and does not equal the previous value, perform the following validations
    if (newValue) {
        if (newValue != oldValue) {
            var x = newValue;

            if (x.length == 4) {
                // If the length of the value is 4 characters, place "ext " in front of the number
                x = x.replace(/[^\d]+/g, '');
                x = x.replace(/(\d{4})/, 'ext $1');
                g_form.setValue('u_phone_number', x);
            } else if (x.length == 10) {
                // If the length of the value is 10 characters, format the number as (###) ###-####
                x = x.replace(/[^\d]+/g, '');
                x = x.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
                g_form.setValue('u_phone_number', x);
            } else if (x.length == 11) {
                // If the length of the value is 11 characters, format the number as (###) ###-####
                x = x.replace(/[^\d\s]+/g, '');
                x = x.replace(/(\d{1})?(\d{3})(\d{3})(\d{4})/, '($2) $3-$4');
                g_form.setValue('u_phone_number', x);
            } /*else {
                alert('Please enter a phone number of 4, 10, or 11 digits, no other characters and it will be properly formatted.');
                g_form.setValue('u_phone_number', '');
            } */
        }
    }
}

0 个答案:

没有答案