我想验证文本字段"用户名"下面粘贴代码的形式。验证是使用户名文本字段为必填项。
我在这里遇到的问题是文本字段未经过验证并且点击了提交按钮它直接转移到下一页" index.html&#34 ; 。有人可以建议我如何在下面的代码中更正此问题?我希望首先发生验证然后再通过验证,然后用户可以转到下一页。
我的代码:
<html>
<head>
<script>
//validation for username to be a mandatory field
function ValidateContactForm()
{
var name = document.ContactForm.userid;
if (userid.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
</script>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:30pt;
color:#00FF00;>
<strong>Welcome</strong>
</h1>
<form name="login">
Username: <input type="text" name="userid "/><br/>
Password: <input type="password " name="pswrd"/><br/><br/><br/><br/>
</form>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar = form.submit();
}
</SCRIPT>
</HEAD>
<BODY>
<form method="post" action="index.html" name="ContactForm" onsubmit="return ValidateContactForm();">
<input type="submit" value="Submit">
<input type="reset" value="Cancel"/>
</form>
</BODY>
</HTML>
答案 0 :(得分:0)
您可以使用文本框中的新HTML5 required
属性来制作表单,而不是使用自定义JavaScript来验证表单(不应该依赖它来实际验证表单,因为它可以被绕过)在客户端需要。
答案 1 :(得分:0)
<input type="text" id="userid" />
<input type="password" id="pswrd" />
$("form").submit(event, function() {
var userId = $("#userid");
if (userId.val() == '')
{
alert("Please enter your name.");
userId.focus();
event.preventDefault();
}
}
答案 2 :(得分:0)
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
&#13;
.error {
color: #E00000;
}
&#13;
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
&#13;