【问题标题】:Optimizing JavaScript Code [closed]优化 JavaScript 代码 [关闭]
【发布时间】:2016-04-29 19:08:35
【问题描述】:

我编写了以下 JS,它完成了工作,但我在消除重复代码时遇到了很多麻烦。我一直在破坏功能。

这只是使用regex 进行字段验证,如果输入与regex 不匹配,则在相应字段下方添加错误消息。这是可行的,但我真的想开始编写更简洁的代码。

如果有人可以帮我做这件事,我可以比较我的和你的,并开始了解如何处理这类任务。

谢谢。

<form></form>

这是我的 JSFiddle 代码:https://jsfiddle.net/robinburrage/cnL2d4w8/2/

【问题讨论】:

  • 请在此处发布您的代码。
  • @j08691 这个问题在代码审查中会严重偏离主题。请阅读我们的on-topic help centre 并在推荐 CR 时更加小心。

标签: javascript regex validation


【解决方案1】:

您可以对所有 2 个验证重复使用相同的函数。这 3 个函数之间的唯一区别是您尝试附加到不同的 id。

使用this 而不是专门引用元素,因为输入无论如何都绑定到您要查找的元素。

phone.addEventListener('keyup', validatePhone);
phone2.addEventListener('keyup', validatePhone);
phone3.addEventListener('keyup', validatePhone);

function validatePhone(evt) {    
    var pattern = /^(\(\d{1,2}\)\s)?\(?\d{4}\-\)?[\s.-]?\d{4}$/; //set the regular expression
    var str = this.value; //get the user's input
    var phoneVal = document.getElementById("phoneVal");
    if (phoneVal) { //if the error message div is already on the page
        phoneVal.parentNode.removeChild(phoneVal); //remove it, to prevent a series of error message divs from accumulating
    }
    if (str === "") {//if there is no user input
        phoneVal.parentNode.removeChild(phoneVal);//remove the error message
    }
    if (pattern.test(str) === false) { //if the string doesn't match the expression            
        var elem = document.createElement("div"); //create a DIV
        elem.setAttribute("id", "phoneVal"); //give it an 1)id, 2)class and 3)message
        elem.setAttribute("class", "form-error-msg");   
        if(window.location.href.indexOf("/en") > -1) {
            elem.innerHTML = 'Please enter a valid telephone number.'; 
        }else{
            elem.innerHTML = 'Por favor introduce un número de teléfono válido.'; 
        }            
        this.parentNode.appendChild(elem); //add the div with the current error message
    }   
} //end function

【讨论】:

  • 哦,不。我只是注意到,即使我正在测试一个似乎在 debuggex.com 中运行良好的正则表达式,在我的代码中(在上面的 JSFiddle 链接中),即使用户输入字母,错误消息也会消失。我知道错误消息的隐藏和显示与实际的验证部分完全分开,所以一个可能与另一个无关,但是任何人都可以解释一下吗?
猜你喜欢
  • 2017-02-18
  • 2011-11-02
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多