why do I have this problem? I'm trying to get an output to the user name in the site. but it keeps giving me this problem!
I ant it to write me that the user name is not correct when im starting with a number or it is blanked at all- it gives me nothing.
please help me I am sitting on this above an hour:((
Snippet
function validateForm() {
var res = true;
res = userNameVal() && res;
return res;
}
function userNameVal() {
var userName = document.getElementById("username").value;
var msgBox = document.getElementById("userNameCheck");
if (userName.length == 0) {
msgBox.innerHTML = "You must enter user name";
msgBox.style.color = "red"
return false;
}
if (!isLetter(userName[0])) {
msgBox.innerHTML = "User name must start with a letter ";
msgBox.style.color = "red";
return false;
}
msgBox.innerHTML = "";
return true;
}
<form id="form1" method="post" onsubmit="return validateForm()">
<table class="table3">
<tr>
<td>
<label for="username">User Name:</label>
</td>
<td>
<input type="text"
name="username"
id="username"
onchange="userNameVal()" />
</td>
<td>
<div id="userNameCheck"></div>
</td>
</tr>
<tr>
<td><input type="button"
value="submit"
onclick="return validateForm()"/>
<input type="reset" value="reset" />
</td>
<td></td>
<td></td>
</tr>
</table>
</form>
Related
I have been looking at some examples of form validation, where an invalid input will stop the user before proceeding to the next page. The way I have seen this done many times is using the event.preventDefault() function, but it just doesn't seem to be working for me. I'm not sure if the javascript function is wrong, or maybe it is just not being read at all. When I send in an invalid input it goes through to the next page anyway.
Here is my HTML code:
Header:
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="3.css"/>
<script type="text/javascript" src="3.js"></script>
<title>Login</title>
Body:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="submit" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
and here is the referenced 3.js code:
document.getElementById("loginForm").addEventListener("submit", loginFunction, false);
function loginFunction(event)
{
var valid= true;
var elements= event.currentTarget;
var email= elements[0].value;
var pass= elements[1].value;
var regexEmail= /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass= /^(\S*)?\d+(\S*)?\W+$/;
var emailError= document.getElementById(emailError);
var passError= document.getElementById(passError);
if (email == null || email == ""){
emailError.innerHTML= "Email is empty";
valid= false;
}
else if (regexEmail.test(email) == false){
emailError.innerHTML= "Incorrect Email format";
valid= false;
}
if (pass == null || pass == ""){
passError.innerHTML= "Password is empty.";
valid = false;
}
else if (regexPass.test(pass) == false) {
passError.innerHTML= "Incorrect password format";
valid = false;
}
else if (pass.length < 8){
passError.innerHTML= "Password is too short, must be 8+ characters";
valid= false;
}
if (valid == false){
event.preventDefault();
}
}
Can anyone explain where i've made my error?
This should do the trick:
<section>
<h2>Login</h2>
<div id="loginInfo">
<form id="loginForm" method="post" action="nextpage.php" enctype="multipart/form-data">
<table id="loginTable">
<tr>
<td>
<input type="text" class="loginInput" id="loginEmail" name="loginEmail" placeholder="Email">
</td>
</tr>
<tr>
<td><label id="emailError" class="errorMsg"></label></td>
</tr>
<tr>
<td>
<input type="password" class="loginInput" id="loginPassword" name="loginPassword" placeholder="Password">
</td>
</tr>
<tr>
<td><label id="passError" class="errorMsg"></label></td>
</tr>
<tr>
<td></br><input type="button" name="submit" id="loginSubmit" value="Login"></td>
</tr>
</table>
</form>
</div>
</section>
And this:
document.getElementById('loginSubmit').addEventListener('click',loginFunction,false);
function loginFunction()
{
var valid=true;
var elements=event.currentTarget;
var email=elements[0].value;
var pass=elements[1].value;
var regexEmail=/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
var regexPass=/^(\S*)?\d+(\S*)?\W+$/;
var emailError=document.getElementById(emailError);
var passError=document.getElementById(passError);
if(email==null||email=='')
{
emailError.innerHTML='Email is empty';
valid=false;
}
else if(regexEmail.test(email)==false)
{
emailError.innerHTML='Incorrect Email format';
valid=false;
}
if(pass==null||pass=='')
{
passError.innerHTML='Password is empty.';
valid=false;
}
else if(regexPass.test(pass)==false)
{
passError.innerHTML='Incorrect password format';
valid=false;
}
else if(pass.length<8)
{
passError.innerHTML='Password is too short, must be 8+ characters';
valid=false;
}
if(!valid)
{
return
}
document.getElementById('LoginForm').submit();
}
I have the next input field:
<form action="admin" method="POST" commandName="adminForm" onsubmit="return validateEmail(this.email)">
<table>
<tr>
<td>
<label for="email">Email</label>
</td>
<td>
<input id="email" name="email" type="text" path="email" oninvalid="this.setCustomValidity('Please fill this field - it is mandatory')" oninput="setCustomValidity('')">
</td>
</tr>
</table>
</form>
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!re.test(email.value)) {
email.setAttribute("oninvalid", "this.setCustomValidity('Wrong email format')");
email.setAttribute("oninput", "setCustomValidity('')");
return false;
}
return re.test(email.value);
}
Here I want to display error message when the wrong email is added. Now when I do not add something under the email field, it shows error Please fill this field - it is mandatory. I want to change this message if email is wrong.
It currently does not work, any ideas why?
Refer to my example source.
html
<form id="myForm" action="admin" method="POST">
<table>
<tr>
<td>
<label for="email">Email</label>
</td>
<td>
<input id="email" name="email" type="text">
</td>
</tr>
</table>
<div id="msg"></div>
<button type="submit">submit</button>
</form>
and javascript
var form = document.getElementById('myForm');
var msg = document.getElementById('msg');
form.addEventListener('submit', function( e ) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = document.getElementById('email').value;
if (!re.test(email)) {
console.log('invalid');
msg.innerText = 'invalid email';
e.preventDefault();
} else {
msg.innerText = '';
}
});
and live demo
I am struggling to understand where there is a mistake.
After many tries, I tend to think that it's something about overalcheck()...
The append, clearelement and writeto are the additional mini functions and they are totally fine.
So, this script checks the form, and if everything is ok, opens a new page. However, if a field is empty or has a wrong type, it shows the relative error message (or a list of error messages).
I made a lot of variations, sometimes it opens without a completed form (like the code below), sometimes it shows the error message for 1 field only and then, and even if you complete all fields, it still doesnt open a new page.
I would appreciate your help.
<script>
function overallcheck ()
{
if(!checkname() || !checkemail() || !checkjob())
{
writeTo("problemArea","Error messages area");
if(!checkname())
writeTo("problemArea","Please insert a valid name");
if(!checkemail())
writeTo("problemArea","Please insert a valid email");
if(!checkjob())
writeTo("problemArea","Please insert your job");
return false;
}
return true;
}
function checkname()
{
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkemail()
{
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
function checkjob()
{
clearElement("problemArea");
var i;
for (i=0;i<4;i++)
{
if (document.forms['form'].job[i].checked) {return true;}
}
return false;
}
</script>
<body>
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b> </td>
<td> <input type="text" name="fullname" size="20" placeholder="Enter a valid name"/> </td>
</tr>
<tr>
<td><b><p> E-mail: </p></b></td>
<td><input type="email" name="email" maxlength="15" size = "20" placeholder="Enter a valid email address"/> </td>
</tr>
<tr>
<p><td><b><p>bla?</td></p>
<td>1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/><div id="problemArea"> </div>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
</body>
</html>
Track each error type with it's own div. Wrap overallcheck in a try catch to and alert errors. This helped find the "Email" error.
function writeTo(id, msg) {
document.getElementById(id).innerHTML += "<p>" + msg + "</p>";
}
function clearElement(id) {
document.getElementById(id).innerHTML = "";
}
function overallcheck() {
try {
if (!checkname() || !checkemail() || !checkjob()) {
if (!checkname())
writeTo("problem_fullname", "Please insert a valid name");
if (!checkemail())
writeTo("problem_email", "Please insert a valid email");
if (!checkjob())
writeTo("problem_blah", "Please insert your job");
return false;
}
return true;
} catch (err) {
alert(err);
}
}
function checkname() {
clearElement("problem_fullname");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname)) {
return false;
}
return true;
}
function checkemail() {
clearElement("problem_email");
var mail = document.forms['form'].email.value; //Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1) {
return false;
}
return true;
}
function checkjob() {
clearElement("problem_blah");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
td {
vertical-align: text-top;
}
.problem {
color: red;
}
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b>
</td>
<td>
<input type="text" name="fullname" size="20" placeholder="Enter a valid name" />
<div id="problem_fullname" class="problem"></div>
</td>
</tr>
<tr>
<td><b><p> E-mail: </p></b>
</td>
<td>
<input type="email" name="email" maxlength="15" size="20" placeholder="Enter a valid email address" />
<div id="problem_email" class="problem"></div>
</td>
</tr>
<tr>
<p>
<td><b><p>bla?</td></p>
<td>
1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
<div id="problem_blah" class="problem"> </div>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
I am currently using html to code a 'form entry'. I am also using a JavaScript validation, to validate the input in of the form. At the moment, i have 'name', 'subject' and 'examination number', each working and having functional validations. However i need to add a validation for 'qualification'. The type of input has to be click select and the 'qualification' has to be radio buttons. there should be three radio buttons called 'GCSE', 'AS' and 'A2'. it would be great if someone could help me with the radio buttons, and the user should only be able to click and select one type of qualification at one time. after clicking the qualification, the user needs to be informed by a message that they have chosen their qualification 'you have selected GCSE as your qualification' this message should be immediately after they clicked their qualification. GCSE is just an example, it could be AS or A2 or GCSE. thanks.
here is my code: the radio buttons are near the bottom, but the validaiton should be below the validation of 'examination number'
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width="60%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td id="qualification">Choose your qualification</td>
<tr>
<td>
<input type="radio" name="group1" value="GCSE">GCSE<br>
</td>
</tr>
<tr>
<td>
<input type="radio" name="group1" value="AS">AS<br>
</td>
</tr>
<tr>
<td>
<input type="radio" name="group1" value="A2">A2<br>
</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
Here is how to add radio validation to your code. (Note this is setup for name="group1" radios only, you will need a for loop to check group2, group3, etc.)
if (document.ExamEntry.group1.value=="") {
msg+="You must choose a qualification\n";
document.ExamEntry.subject.focus();
document.getElementById('radioqual').style.color="red";
result = false;
}
You notify the user of what qualification they clicked by onclick events on each radio.
The function
function qualinform(qualname) {
alert(qualname + " was selected as your qualification.");
}
Example of a radio button (The name should be put into the onclick parameters)
<input onclick="qualinform('GCSE');" type="radio" name="group1" value="GCSE">GCSE
Here is the complete code.
<html>
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function qualinform(qualname) {
alert(qualname + " was selected as your qualification.");
}
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.group1.value=="") {
msg+="You must choose a qualification\n";
document.ExamEntry.subject.focus();
document.getElementById('radioqual').style.color="red";
result = false;
}
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width="60%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td id="qualification">Choose your qualification</td>
<tr>
<td id="radioqual">
<input onclick="qualinform('GCSE');" type="radio" name="group1" value="GCSE">GCSE<br>
<input onclick="qualinform('AS');" type="radio" name="group1" value="AS">AS<br>
<input onclick="qualinform('A2');" type="radio" name="group1" value="A2">A2<br>
</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
Loop over each of the form elements named 'qualification', and when you find the checked one, grab its value and push it into your validation message like this:
var qualifications = document.getElementsByName('group1')
for (var i = 0, length = qualifications.length; i < length; i++) {
if (radios[i].checked) {
msg+='you have selected ' + radios[i].value + ' as your qualification.';
break;
}
}
Okay I have a solution for you :) Try this
Then allocate ids to your inputs as a1, a2 & a3
<script language="javascript" type="text/javascript">
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}
if(document.getElementById('a1').checked){
if (msg != "") {
alert(msg);
}
return result;
}
else{
if(document.getElementById('a2').checked){
if (msg != "") {
alert(msg);
}
return result;
}
else{
if(document.getElementById('a3').checked){
if (msg != "") {
alert(msg);
}
return result;
}
else{
msg+="Please select an option";
result = false;
if (msg != "") {
alert(msg);
}
return result;
}
}
}
}
</script>
I want to know how can i live validate radio button like text box on click event or on key up or press event? Like textbox, when we start typing and if it passes validation, then error message is gone; in the same way i want to implement this functionality for radio button. I have the following code which works only for textbox on keyup event and not for radio buttons -
HTML -
<form name="form1" id="form1" method="post" action="">
<table border="0" align="center" width="50%" cellpadding="5">
<tr>
<th align="right" valign="top"><label for="txtemail">Email ID:</label></th>
<td>
<input type="text" name="txtemail" id="txtemail" size="30" onKeyUp="return isValid();" />
<span id="erremail"></span>
</td>
</tr>
<tr>
<th align="right" valign="top"><label>Gender:</label></th>
<td>
<input type="radio" name="gender" id="radmale" value="Male" onClick="this.checked; return isValid();" />
<label for="radmale">Male</label>
<input type="radio" name="gender" id="radfemale" value="Female" onClick="return isValid();" />
<label for="radfemale">Female</label>
<span id="errgender"></span>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="btnsubmit" value="Register" onClick="return isValid();">
</td>
<td>
<input type="reset" value="Clear Form">
</td>
</tr>
</table>
</form>
JavaScript -
<script type="text/javascript">
var flag;
function isValid()
{
flag = true;
reqdField("txtemail", "erremail", "Email ID is empty");
isValidEmail("txtemail", "erremail", "Email ID is not valid", /^[a-z0-9_.-]+#[a-z-.]+\.[a-z.]{2,5}$/);
checkGender("radmale", "radfemale", "errgender", "Select your gender");
return flag;
}
// checking all required fields
function reqdField(ctrid, errid, errmsg)
{
var str = document.getElementById(ctrid).value;
if(str.length == 0)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
// checking is email id valid
function isValidEmail(ctrid, errid, errmsg, validExp)
{
var email = document.getElementById(ctrid).value;
if(email.match(validExp) == null)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
// checking is gender selected
function checkGender(ctrid1, ctrid2, errid, errmsg)
{
var male = document.getElementById(ctrid1);
var female = document.getElementById(ctrid2);
if(male.checked == false && female.checked == false)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
</script>
Another issue I am facing in this code is regarding reqdField() function. This function does work and only isValidEmail() runs. I only see email is not valid when it is left empty and can not display email id is empty. How can i achieve the same?
Here is the demo JSFiddle
<script type="text/javascript">
var flag;
function isValid()
{
flag = true;
reqdField("txtemail", "erremail", "Email ID is empty");
isValidEmail("txtemail", "erremail", "Email ID is not valid", /^[a-z0-9_.-]+#[a-z-.]+\.[a-z.]{2,5}$/);
checkGender();
return flag;
}
// checking all required fields
function reqdField(ctrid, errid, errmsg)
{
var str = document.getElementById(ctrid).value;
if(str.length == 0)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
flag = true;
}
}
// checking is email id valid
function isValidEmail(ctrid, errid, errmsg, validExp)
{
var email = document.getElementById(ctrid).value;
if(email.length == 0){
return;
}else{
if(email.match(validExp) == null)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
flag = true;
}
}
}
// checking is gender selected
function checkGender()
{
var ctrid1="radmale", ctrid2="radfemale", errid="errgender", errmsg="Select your gender"
var male = document.getElementById(ctrid1);
var female = document.getElementById(ctrid2);
if(male.checked == false && female.checked == false)
{
document.getElementById(errid).innerHTML = errmsg;
return false;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
return true;
}
}
</script>
and html is
<form name="form1" id="form1" method="post" action="">
<table border="0" align="center" width="50%" cellpadding="5">
<tr>
<th align="right" valign="top"><label for="txtemail">Email ID:</label></th>
<td><input type="text" name="txtemail" id="txtemail" size="30" onKeyUp="return isValid();" />
<span id="erremail"></span>
</td>
</tr>
<tr>
<th align="right" valign="top"><label>Gender:</label></th>
<td><input type="radio" name="gender" id="radmale" value="Male" onClick="return checkGender();" /><label for="radmale">Male</label>
<input type="radio" name="gender" id="radfemale" value="Female" onClick="return checkGender();" /><label for="radfemale">Female</label>
<span id="errgender"></span>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="btnsubmit" value="Register" onClick="return isValid();"></td>
<td><input type="reset" value="Clear Form"></td>
</tr>
</table>
</form>
Fiddle
$("input[type=radio]").click(function(){
var set = $(this).attr("name");
validateRadioSet(set);
});