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

I want to know how to do form validation in javascript

本文关键字:表单 验证 javascript 想知道      更新时间:2023-09-26

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

// 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变量设置警报,并首先确认

if语句条件x != (>1900 &&<=2012)毫无意义。>1900<=2012的计算结果不是布尔值,因此不能对它们使用&&运算符。你想要的是这样的东西:

x<1900 || x>2012

这会检查x是过低还是过高,然后使用||(或)运算符来检查x是否以任何一种方式无效。

您的代码存在一些语法问题。若你们想得到出生年份的输入值。您不必迭代表单中的元素(就像使用for循环一样),您可以这样做:document.forms[0].elements['birthyear']

此外,当您获得输入元素的值时,它的类型是字符串。在将其与integer类型的值进行比较之前,您应该将字符串转换为integer:

intValue = parseInt(stringValue, 10);

所以你的代码将遵循

<form action="fake.php">Username
    <input class="required" type="text" name="username" id="username" />Birthyear
    <input class="required" type="number" name="birthyear" id="birthyear" />
    <input type="submit" />
</form>
<script>
// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
window.onload = function () {
    document.forms[0].onsubmit = function () {
        var birthYearElem = document.forms[0].elements['birthyear'],
            stringValue = birthYearElem.value,
            intValue = parseInt(stringValue, 10);
        if (intValue < 1900 || intValue > 2012) {
            alert("Must be between 1900 and 2012");
            birthYearElem.style.color = "yellow";
            return false;
        }
    }
}
<script>