要验证并连接,请在表格中输入电话号码

To validate and connvert entered phone number in a form

本文关键字:表格 输入 电话号码 验证 连接      更新时间:2023-09-26

我正在处理一个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> 

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)";>

EDIT上面的代码只是想法,请注意,在您的案例中,在PhoneValidation内部是this = window。你已经通过了手机,所以试着使用它,你可以在这里进行演示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如果您不能通过条件,请通过为您的消息分区设置html

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

仅此而已。希望得到帮助!

if (!(this.isNull)) {

显然,保持简短,比如:

if (this) {