简体   繁体   English

如何使用 Javascript 验证 HTML 表单

[英]How to validate HTML form with Javascript utilisation

Hey guys im currently stuck on HTML Form Validation using Javascript which i find confusing.嘿伙计们,我目前坚持使用 Javascript 进行 HTML 表单验证,这让我感到困惑。 Any help would be immensely appreciated.任何帮助将不胜感激。 The form requirements for this task are as follows:此任务的表格要求如下:

All fields are required (except student id, and if the user is younger than 18 years old so is identification type and number)所有字段都是必填字段(学生证除外,如果用户未满 18 岁,则身份类型和编号也是必需的)

  • A title must be selected必须选择标题
  • University email address is in a valid email address format大学电子邮件地址采用有效的电子邮件地址格式
  • A valid date must be entered for date of birth必须为出生日期输入有效日期
  • Using the date of birth entered, a calculation must determine if the user is 18 or more years old.使用输入的出生日期,计算必须确定用户是否年满 18 岁。 If determined to be 18 or more years old the user must select an identification type and enter an identification number.如果确定为 18 岁或以上,用户必须选择识别类型并输入识别号。 Based on the identification type chosen will determine the format of identification number required:根据选择的识别类型将确定所需的识别号格式:
    • Drivers License: ####XX驾照: ####XX
    • Proof of Age: #X###X年龄证明: #X###X
    • # Means a digit number, X means any capital alphabetical letter #表示数字,X 表示任意大写字母
  • 1 or more days of attendance must be selected必须选择出勤1天或更多天

The form should not submit unless the requirements are met and required fields should show their corresponding error messages.除非满足要求,否则不应提交表单,并且必填字段应显示其相应的错误消息。

I have tried to make javascript work with some corresponding css but have no luck yet.我试图让 javascript 与一些相应的 css 一起工作,但还没有运气。 Here is what I have done so far:这是我到目前为止所做的:

function validateForm(form) {

    var valid = true;
    if (!form.fname.value.length) {
        valid = false;
        document.getElementById('fnameRequired').style.display = "inline-block";
        form.fname.style.border = "1px solid #ff0000";
    } else {
        document.getElementById('fnameRequired').style.display = "none";
        form.fname.style.border = "1px solid #ccc";
    }

    if (!form.lname.value.length) {
        valid = false;
        document.getElementById('lnameRequired').style.display = "inline-block";
        form.lname.style.border = "1px solid #ff0000";
    } else {
        document.getElementById('lnameRequired').style.display = "none";
        form.lname.style.border = "1px solid #ccc";
    }
}

you should validate by CSS before using javascript https://webdevtrick.com/html-css-form-validation/在使用 javascript https://webdevtrick.com/html-css-form-validation/之前,您应该通过 CSS 进行验证

there are many ways to check the input, especially for standard types like EMAIL URL NUMBER it is even easier有很多方法可以检查输入,特别是对于像 EMAIL URL NUMBER 这样的标准类型,它更容易

HTML 表单可以通过外部或内部 CSS 链接进行验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM