gpt4 book ai didi

javascript - 为什么我的 Javascript 验证不起作用?

转载 作者:行者123 更新时间:2023-11-30 10:54:29 24 4
gpt4 key购买 nike

<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var username = document.getElementByName('username');
var password = document.getElementByName('password');
var email = document.getElementByName('email');

// Check each input in the order that it appears in the form!
if(isAlphanumeric(username, "Please only use letters and numbers for you username.")){
if(lengthRestriction(username, 8, 12)){
if(lengthRestriction(password, 6, 15)){
if(emailValidator(email, "Please enter a valid email address")){
return true;
}
}
}
}


return false;
}


function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}

function emailValidator(elem, helperMsg){
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

我的脚本不工作,即使用户名、密码和电子邮件文本框已经定义了名称属性。谢谢 :)。

最佳答案

getElementByName不是 document 的有效方法目的。你要getElement<em><b>s</b></em>ByName , 它将返回具有指定 name 的元素集合属性,或 getElementById()这将返回具有指定 id 的单个元素属性。

// get the first element with name="username"
var username = document.getElementsByName('username')[0];

// get the first element with name="password"
var password = document.getElementsByName('password')[0];

// get the first element with name="email"
var email = document.getElementsByName('email')[0];

关于javascript - 为什么我的 Javascript 验证不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2988542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com