验证并转换表单中输入的电话号码

时间:2014-03-15 13:13:02

标签: javascript regex html5

我正在处理一个HTML表单,其中有4个字段,如下所示

Name
Email
Phone Number
Message

电话号码字段应接受10位数字。当我点击“消息”字段时,它会更改/接受格式(xxx) xxx-xxxx

我已经编写了javascript函数,但是当我点击消息字段时,数字没有改变。代码在

之下

如果有人可以帮我解决这个问题,那将是一个很大的帮助。提前谢谢!

function PhoneValidation(phone) {
  if (!(this.isNull)) {

    var str = this.rawValue;

    var regExp = /^\d{10}$/;

    if (regExp.test(str)) {

      this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(3, 3) + "-" + str.substr(6, 4);

    } else {

      regExp = /^[1-9]\d{2}\s\d{3}\s\d{4}$/;

      if (regExp.test(str)) {

        this.rawValue = "(" + str.substr(0, 3) + ") " + str.substr(4, 3) + "-" + str.substr(8, 4);

      } else {

        regExp = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;

        if (!(regExp.test(str))) {

          xfa.host.messageBox("Please enter the telephone number in the format '(999) 999-9999'.");

          this.rawValue = null;

          xfa.host.setFocus(this);

        }

      }

    }

  }
}

以下HTML:

<form id="contact-form" class="contact-form" method="post" action="">
    <div class="result"></div>
    <input type="text" name="contact[name]" id="name" placeholder="Name *">
    <input type="text" name="contact[email]" id="email" placeholder="E-mail *">
    <input type="text" name="phone" id="phone" placeholder="Phone" onChange="PhoneValidation(this)" ;>
    <textarea cols="5" rows="5" name="contact[message]" id="message" placeholder="Message *"></textarea>
    <input type="submit" class="btn-dark" value="SEND">
</form> 

2 个答案:

答案 0 :(得分:1)

在您的validate函数this = window或其他内容中,因此我不知道!this.isNull实际会做什么。

您可以将其更改为

function PhoneValidation(phone) {
   if(phone.value) {
         // set up the phone.value here
   }
}
// bind the change event as you did.
<input type="text" name="phone" id="phone"  placeholder="Phone" onChange="PhoneValidation(this)";>

编辑上面的代码就是这个想法,请注意您的案例this = window内的PhoneValidation。您已通过电话,因此尝试使用它,您可以在此处进行演示http://jsfiddle.net/7qjz2/。作为总结

window.PhoneValidation = function(phone)
// cause I don't know where you put this js, so let bind it to window.

在旁边函数中,rawValue未定义,因此请改用phone.value 如果您无法通过该条件,请为您的消息div设置html。由

document.getElementById("result").innerHTML = "Whatever you want"

这就是全部。希望这有帮助!

答案 1 :(得分:0)

if (!(this.isNull)) {

显然,保持简短和简单:

if (this) {
相关问题