使用类在JS中进行多表单验证



我想验证两个html表单-第一个表单在FAQ页面上,第二个表单在联系我们页面上。这两个表单都有name和phone作为公共输入字段,所以我想通过使用Class在JS中方便地验证这两个窗体。

我的JS代码如下所示,用于验证常见问题表单的名称和电话输入字段

class FormValidate {
constructor(nameField, phoneField,  emailField, form) {
this.nameField = nameField;     // name input field
this.phoneField = phoneField;   // phone input field
this.emailField = emailField;   // email input field
this.form = form;
}
// method for validation of name input
validateName(nameField) {
const regName = new RegExp("^[a-zA-Z\s]*$");
let isNameValid = false;
let name_z = nameField.value.trim(); // input value of Name input field
let isNameHasValidLength = name_z.length < 3 || name_z.length > 20 ? false : true;
// Name input field is not empty and contain proper data -> Not Empty && value must be between 3 to 20 characters && follow reg expression for validation
if( !(name_z === '') && isNameHasValidLength && (regName.test(name_Z)) ){
isNameValid = true;
}
return isNameValid;
}
validatePhone(phoneField) {
let isPhoneValid = false;
let phone_z = phoneField.value.trim(); // input value of Phone input field
let isPhoneHasValidLength = phone_z.length < 10 || phone_z.length > 13 ? false : true;  // making sure that phone number is between 10 to 13 digits -> +91 and rest 10 digits
const regPhone = new RegExp("^([0|+[0-9]{1,5})?([7-9][0-9]{9})$");
// Validating Phone Number -> Not Empty && Must have 10 to 13 digits only && follow reg expression for validation
if( !(phone_z === '') && isPhoneHasValidLength && regPhone.test(phone)) {
isPhoneValid = true;
}
return isPhoneValid;
}
}
let faqForm = new FormValidate(document.querySelector('#name'), document.querySelector('#phone'), null, document.querySelector('#faq-form'));
faqForm.form.addEventListener('submit', function(e) {
let nameOkay;
let phoneOkay;
let submitOkay;
nameOkay = faqForm.validateName(faqForm.nameField);
phoneOkay = faqForm.validatePhone(faqForm.phoneField);
submitOkay = nameOkay && phoneOkay;
// Prevent form submission if form input is not okay
if (!submitOkay) {
e.preventDefault();
}
});

HTML表单代码-

<form id="faq-form" action="mail-faq.php" method="POST">
<div class="faq-form-group"> <span class="faq-form-span-text">Name</span>
<input type="text" placeholder="i.e, John Smith" name="name" id="name" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Phone</span>
<input type="text" placeholder="+91 123456789" name="phone" id="phone" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Message</span>
<textarea placeholder="Your question" name="message" id="message" autocomplete="off" required></textarea>
</div>
<div class="faq-form-group">
<button class="faq-form-submit-btn" id="submit" type="submit" name="submit">Submit </button>
</div>
</form>

问题是nameField.value.trim();phoneField.value.trim();语句返回值-"",这使得验证为false。

如何解决此问题?

当您在(regName.test(name_Z))(小写z(中更正此处的拼写错误时,三聚变量与预期的一样(而不是"(。。。

相关内容

  • 没有找到相关文章

最新更新