我的任务是为JavaScript正则表达式电话验证检查器编写if/else
结构,我遇到了问题。我的约束和格式如下:
我试图去除除数字之外的所有字符,然后通过正则表达式处理它。当我将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', '');
} */
}
}
}