javascript - 我想知道如何在 javascript 中进行表单验证

标签 javascript validation

我正在尝试学习表单验证,但它不起作用。

// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
        window.onload = function() {
        document.forms[0].onsubmit = function() {
        for(i = 0; i < document.forms[0].elements.length; i++){

       var x =
       document.forms[birthyear].value

    if (x != (>1900 &&<=2012)){
    alert("Must be between 1900 and 2012");
    x.this.style.color ="yellow";
    return false;

//这就是我创建表单的方式:

<form action = "fake.php"></br>

    Username  
   <input class ="required"type = "text" name = "username" id ="username" /><br>
   Username
   <input class = "required"type = "text" name ="username"id ="username"/>   <br>


Birthyear
<input class  = "required" type = "number" name = "birthyear" id= "birthyear"/>

<input type = "submit"/>
</form>

最佳答案

if(x<1900 || x> 2012){
    alert("invalid year");

使用这样的 if 语句并尝试

并检查变量 x 是否采用用户正确输入的值。 只需对 x 变量发出警报并首先确认

关于javascript - 我想知道如何在 javascript 中进行表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333125/

相关文章:

javascript - 如何在 Highcharts 同步图表中仅显示一个 x Axis 标签

javascript - javascript 中的以下语句是否等效?

javascript - React 和 Axios : Unable to render array values in UI but I can console. 记录它们

validation - 训练数据的分布与测试/预测的分布

java - Spring 验证: Difference between validation annotations in Class Attributes VS Constructor Parameters

validation - 本地化 MVC3 验证消息

javascript - 一次切换一个元素时遇到问题 (jQuery)

javascript - 基于文本的多人游戏

php - Laravel 在自定义验证规则上附加规则

forms - 将 $html->tagErrorMsg 从 CakePhp 1.1 更新到 1.2