[英]To validate and connvert entered phone number in a form
我正在處理具有以下4個字段的HTML表單
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)";>
編輯上面的代碼僅是個主意,請注意,在您的情況下,在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
如果無法通過條件,請為消息div設置html。 通過
document.getElementById("result").innerHTML = "Whatever you want"
就這樣。 希望有幫助!
if (!(this.isNull)) {
顯然,使其簡短而簡單,例如:
if (this) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.