How do I make an input field accept only letters in javaScript? - javascript

function validate() {
if(document.myForm.name.value =="" ){
alert("Enter a name");
document.myForm.name.focus();
return false;
}
This is what I've written it for an empty string, now i need it to accept only letters?

If you want only letters - so from a to z, lower case or upper case, excluding everything else (numbers, blank spaces, symbols), you can modify your function like this:
function validate() {
if (document.myForm.name.value == "") {
alert("Enter a name");
document.myForm.name.focus();
return false;
}
if (!/^[a-zA-Z]*$/g.test(document.myForm.name.value)) {
alert("Invalid characters");
document.myForm.name.focus();
return false;
}
}

function alphaOnly(event) {
var key = event.keyCode;
return ((key >= 65 && key <= 90) || key == 8);
};
or
function lettersOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode > 31 && (charCode < 65 || charCode > 90) &&
(charCode < 97 || charCode > 122)) {
alert("Enter letters only.");
return false;
}
return true;
}

Try this:
var alphaExp = /^[a-zA-Z]+$/;
if(document.myForm.name.match(alphaExp))
{
//Your logice will be here.
}
else{
alert("Please enter only alphabets");
}
Thanks.

Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.

dep and clg alphabets validation is not working
var selectedRow = null;
function validateform() {
var table = document.getElementById("mytable");
var rowCount = table.rows.length;
console.log(rowCount);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
return false;
}
var mail = /[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id")
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var dept = "`##$%^&*()+=-[]\\\';,./{}|\":<>?~_";
if (dept.match(a)) {
alert("special charachers found");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
console.log(table);
var row = table.insertRow(rowCount);
row.setAttribute('id', rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
cell0.innerHTML = rowCount;
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
cell4.innerHTML = a;
cell5.innerHTML = b;
cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';
}
function emptyfunction() {
document.getElementById("usrname").value = "";
document.getElementById("usremail").value = "";
document.getElementById("usrage").value = "";
document.getElementById("usrdpt").value = "";
document.getElementById("usrclg").value = "";
}
function onEdit(x, y, z, a, b, rowCount) {
selectedRow = rowCount;
console.log(selectedRow);
document.forms["myform"]["usrname"].value = x;
document.forms["myform"]["usremail"].value = y;
document.forms["myform"]["usrage"].value = z;
document.forms["myform"]["usrdpt"].value = a;
document.forms["myform"]["usrclg"].value = b;
document.getElementById('Add').style.display = 'none';
document.getElementById('update').style.display = 'block';
}
function deletefunction(rowCount) {
document.getElementById("mytable").deleteRow(rowCount);
}
function onUpdatefunction() {
var row = document.getElementById(selectedRow);
console.log(row);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
document.myForm.x.focus();
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
document.myForm.y.focus();
return false;
}
var mail = /[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id");
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
document.myForm.z.focus();
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (a.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (b.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
row.cells[1].innerHTML = x;
row.cells[2].innerHTML = y;
row.cells[3].innerHTML = z;
row.cells[4].innerHTML = a;
row.cells[5].innerHTML = b;
}
<html>
<head>
</head>
<body>
<form name="myform">
<h1>
<center> Admission form </center>
</h1>
<center>
<tr>
<td>Name :</td>
<td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
</tr>
<tr>
<td> Email ID :</td>
<td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^#]+#[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
</tr>
<tr>
<td>Dept :</td>
<td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
</tr>
<tr>
<td>College :</td>
<td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
</tr>
</center>
<center>
<br>
<br>
<tr>
<td>
<Button type="button" onclick="validateform()" id="Add">Add</button>
</td>
<td>
<Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
</td>
<td><button type="reset">Reset</button></td>
</tr>
</center>
<br><br>
<center>
<table id="mytable" border="1">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Email ID</th>
<th>Age</th>
<th>Dept</th>
<th>College</th>
</tr>
</center>
</table>
</form>
</body>
</html>

Related

JavaScript validation form integratation into one

I have a form with inputs
Fist name
Last name
Password
Etc
Current my validation works one by one. I would like to integrate them into one pop up box.
Example currently:
All not filled up; upon submission it would pop up First name not filled. I want it to be First name not filled, last name not filled etc
function validateForm() {
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
alert("First Name must be filled out");
return false;
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
alert("Last Name must be filled out");
return false;
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
alert("Please enter a valid email address.");
return false;
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
alert("Please enter a at least 8 alphanumeric characters");
return false;
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
alert('Agree to privacy agreement must be checked');
} else {
status = true;
}
return status;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function validateForm() {
var regexEmail = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var regexMinThree = /^[A-Za-z0-9_ ]{3,13}$/;
var userFirstName = $.trim($('.firstName').val());
var userLastName = $.trim($('.lastName').val());
var userEmail = $.trim($('.email').val());
var userPassword = $.trim($('.password').val());
var msg = '';
if(!regexMinThree.test(userFirstName)) {
msg = 'FirstName, ';
} else {
msg = '';
}
if(!regexMinThree.test(userLastName)) {
msg = msg+'LastName, ';
} else {
msg = msg+'';
}
if(!regexEmail.test(userEmail)) {
msg = msg+'Email, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword)) {
msg = msg+'Password, ';
} else {
msg = msg+'';
}
if(!regexMinThree.test(userPassword) || !regexEmail.test(userEmail) || !regexMinThree.test(userLastName) || !regexMinThree.test(userFirstName)) {
msg = msg+'not filled correctly.';
alert(msg);
}
}
</script>
<form class="userRegistrationForm" onsubmit="return false;" method="post">
<input type="text" class="firstName" placeholder ="FirstName"/>
<input type="text" class="lastName" placeholder ="LastName"/>
<input type="email" class="email" placeholder ="Email"/>
<input type="password" class="password" placeholder ="Password"/>
<button type="submit" onclick="validateForm()" class="userRegistration">Submit</button>
</form>
Add a flag called error and a string called errorMessage, then in each if statement, if there is an error, make error = true and append error message.
Then when submitted, if error == true, alert errorMessage
You can add an <ul> in your html form where you want to show errors
Example
<ul class="errorContainer"></ul>
Then JS
function validateForm() {
var errors = "";
var x = document.forms["myForm"]["firstname"].value;
if (x == null || x == "") {
errors +="<li>First Name must be filled out</li>";
}
var x = document.forms["myForm"]["lastname"].value;
if (x == null || x == "") {
errors +="<li>Last Name must be filled out</li>";
}
var status = false;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.forms["myForm"]["email"].value.search(emailRegEx) == -1) {
errors +="<li>Please enter a valid email address.</li>";
}
var status = false;
var paswordregex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (document.forms["myForm"]["password"].value.search(paswordregex) == -1) {
errors +="<li>Please enter a at least 8 alphanumeric characters</li>";
}
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmpassword").value;
if (password != confirmPassword) {
errors +="<li>Passwords do not match.</li>";
}
var checkb = document.getElementById('checkboxid');
if (checkb.checked != true) {
errors +="<li>Agree to privacy agreement must be checked</li>";
}
if(errors!="")
{
$(".errorContainer").html(errors);
return false;
} else {
status = true;
return status;
}
}

Brick-walling on JS form validation

Learning JS more in-depth of late, as I've not had to mess with it work. Trying to code some form validation, and it keeps "stopping" at the first input. Any advice is greatly appreciated. I have tried everything I can think of, read so many articles on form validation and nothing works. If anyone can point out my errors and "why" they're errors it'd be much appreciated. Here's my code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<script language="javascript" type="text/javascript">
function validateForm() {
var validFirst = document.forms["myForm"]["fname"].value;
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
return false;
}
var validLast = document.forms["myForm"]["lname"].value;
if (validLast == null || validLast == "") {
document.getElementById("lastError").innerHTML = "Required Field";
document.getElementById("last").style.backgroundColor = "red";
return false;
}
else if (validLast.length < 2) {
document.getElementById("lastError").innerHTML = "Response too short";
document.getElementById("last").style.backgroundColor = "red";
return false;
}
else if (validLast !== null) {
document.getElementById("lastError").innerHTML = "";
document.getElementById("last").style.backgroundColor = "white";
return false;
}
var validEmail = document.forms["myForm"]["email"].value;
if (validEmail == null || validEmail == "") {
document.getElementById("emailError").innerHTML = "Required Field";
document.getElementById("email").style.backgroundColor = "red";
return false;
}
else if (validEmail.length < 2) {
document.getElementById("emailError").innerHTML = "Response too short";
document.getElementById("email").style.backgroundColor = "red";
return false;
}
else if (validEmail !== null) {
document.getElementById("emailError").innerHTML = "";
document.getElementById("email").style.backgroundColor = "white";
return false;
}
var validPhone = document.forms["myForm"]["phone"].value;
if (validPhone == null || validPhone == "") {
document.getElementById("phoneError").innerHTML = "Required Field";
document.getElementById("phone").style.backgroundColor = "red";
return false;
}
else if (validEmail.length < 2) {
document.getElementById("phoneError").innerHTML = "Response too short";
document.getElementById("phone").style.backgroundColor = "red";
return false;
}
else if (validEmail !== null) {
document.getElementById("phoneError").innerHTML = "";
document.getElementById("phone").style.backgroundColor = "white";
return false;
}
}
</script>
<head>
<title>Form Validation</title>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" id="first" name="fname" onchange="validFirst()"></td>
<td><span id="firstError"></span></td>
</tr>
<td>Last Name</td>
<td><input type="text" id="last" name="lname" onchange="validLast()"></td>
<td><span id="lastError"></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email" onchange="validEmail()"></td>
<td><span id="emailError"></span></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" id="phone" name="phone" onchange="validPhone()"></td>
<td><span id="phoneError"></span></td>
<tr>
<td><input type="submit" value="Submit"></td>
<td></td>
<td></td>
</tr>
</table>
In the last else statement in each section, you're returning the form field to its "non-error" state and then returning false, causing the validation function to exit.
The solution is to remove this last return false; in each group of if/else if blocks:
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
return false;
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
// return false; /**** this is causing your validation function to terminate ****/
}
https://jsfiddle.net/mblase75/75rcwv8k/
Fixed! thanks for the help, everyone!
function validateForm() {
var validFirst = document.forms["myForm"]["fname"].value;
if (validFirst == null || validFirst == "") {
document.getElementById("firstError").innerHTML = "Required Field";
document.getElementById("first").style.backgroundColor = "red";
}
else if (validFirst.length < 2) {
document.getElementById("firstError").innerHTML = "Response too short";
document.getElementById("first").style.backgroundColor = "red";
}
else if (validFirst !== null) {
document.getElementById("firstError").innerHTML = "";
document.getElementById("first").style.backgroundColor = "white";
}
var validLast = document.forms["myForm"]["lname"].value;
if (validLast == null || validLast == "") {
document.getElementById("lastError").innerHTML = "Required Field";
document.getElementById("last").style.backgroundColor = "red";
}
else if (validLast.length < 2) {
document.getElementById("lastError").innerHTML = "Response too short";
document.getElementById("last").style.backgroundColor = "red";
}
else if (validLast !== null) {
document.getElementById("lastError").innerHTML = "";
document.getElementById("last").style.backgroundColor = "white";
}
var validEmail = document.forms["myForm"]["email"].value;
if (validEmail == null || validEmail == "") {
document.getElementById("emailError").innerHTML = "Required Field";
document.getElementById("email").style.backgroundColor = "red";
}
else if (validEmail.length < 2) {
document.getElementById("emailError").innerHTML = "Response too short";
document.getElementById("email").style.backgroundColor = "red";
}
else if (validEmail !== null) {
document.getElementById("emailError").innerHTML = "";
document.getElementById("email").style.backgroundColor = "white";
}
var validPhone = document.forms["myForm"]["phone"].value;
if (validPhone == null || validPhone == "") {
document.getElementById("phoneError").innerHTML = "Required Field";
document.getElementById("phone").style.backgroundColor = "red";
}
else if (validEmail.length < 2) {
document.getElementById("phoneError").innerHTML = "Response too short";
document.getElementById("phone").style.backgroundColor = "red";
}
else if (validEmail !== null) {
document.getElementById("phoneError").innerHTML = "";
document.getElementById("phone").style.backgroundColor = "white";
}
return false;
}
</script>
<head>
<title>Form Validation</title>
</head>
<body>
<form name="myForm" action="" onsubmit="return validateForm()" method="post">
<table>
<tr>
<td>First Name</td>
<td><input type="text" id="first" name="fname" onchange="validFirst()"></td>
<td><span id="firstError"></span></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" id="last" name="lname" onchange="validLast()"></td>
<td><span id="lastError"></span></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" id="email" name="email" onchange="validEmail()"></td>
<td><span id="emailError"></span></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" id="phone" name="phone" onchange="validPhone()"></td>
<td><span id="phoneError"></span></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>

Problems with form validations

<div id="form">
<form method="post" action="register1.aspx" onsubmit="return validateForm();"name="register1" >
<h1>
Register to exess the site</h1>
<input type="text" name="firstname" class=" br"/>
<em>First name</em><br />
<span id="firstnmsg"></span><br />
<input type="text" name="lastname" class=" br" /><em>Last name</em><br />
<span id="lastnmsg"></span><br />
<input type="text" name="username" class=" br" /><em>username</em><br>
<span id="usermsg"></span><br />
<input type="password" name="password" class=" br" /><em>password</em><br />
<input type="password"name="password1" class=" br" /><em>Confirm password</em>
<span id="pass1msg"></span><br />
<input type="text" name="email" class=" br"/><em>Email!</em><br />
<span id="emailmsg"></span><br />
<select name="sex">
<option>Please select a Gender</option>
<option>Male</option>
<option>Female</option>
<em>Gender</em>
</select><br />
<input type="submit" name="submit" value="Register " onclick="return validateForm();" />
<input type="reset" name="reset" value="Reset" onclick="return resetMsg();"/>
</form>
<span> <%=Session["regstatus"] %></span>
</div>
<div id="log_in">
<h1><em>log in</em></h1>
<form action="WebForm2.aspx"method="post" name="log_in" onsubmit="return validateloginform"><br />
<span id="usernamemsg"><%=Session["usernamemsg"] %> </span><input type="text" name="username_1" class="br" /><em>Username</em><br />
<span id="passwordmsg"><%=Session ["passwordmsg"] %></span><input type="password" name="password_1" class="br" /><em>Password</em><br />
<input type="submit" name="submit2" onclick=" validateloginform"/>
</form>
</div>
<script type="text/javascript">
function isEmpty(str) {
return (str.length == 0);
}
function isNumeric(str) {
var c = true;
for (var i = 0; i < str.length; i++) {
c = !(isNaN(str[i]));
}
return c;
}
function isValid(str) {
var badChar = "\\;:!##$%^&*()-_=+`~<>?[]{}|/,.";
for (var l = 0; l < str.length; l++) {
for (var c = 0; c < badChar.length; c++) {
if (str[l] == badChar[c]) {
return true;
}
if (str[l] == " " || str[l] == "\"" || str[l] == "\'") {
return true;
}
}
}
return false;
}
function isShort(str) {
return (str.length < 3);
}
//Reset Error Messages Function -->
function resetMsg() {
document.getElementById("firstnmsg").innerHTML = "";
document.getElementById("lastnmsg").innerHTML = "";
document.getElementById("usermsg").innerHTML = "";
document.getElementById("passwordmsg").innerHTML = "";
document.getElementById("pssword1msg").innerHTML = "";
document.getElementById("emailmsg").innerHTML = "";
document.getElementById("BdateMsg").innerHTML = "";
document.getElementById("UnameMsg").innerHTML = "";
document.getElementById("PwdMsg").innerHTML = "";
document.getElementById("LoginError").innerHTML = "";
return true;
}
//Main Sign Up Form Validation Function -->
function validateForm() {
resetMsg();
var val = true;
//First Name Validation ---------------------------------------->
if (isEmpty(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.firstname.value) || isValid(signup.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.firstname.value)) {
document.getElementById("firstnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Last Name Validation ------------------>
if (isEmpty(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Empty";
val = false;
}
else {
if (isNumeric(register1.lastname.value) || isValid(signup.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Letters Only";
val = false;
}
else {
if (isShort(register1.lastname.value)) {
document.getElementById("lastnmsg").innerHTML = " Too Short";
val = false;
}
}
}
//Username Validation --------------------------------------------->
if (isEmpty(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Empty";
val = false;
}
else {
if (!isNumeric(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Use Numbers";
}
else {
if (isShort(register1.username.value)) {
document.getElementById("usermsg").innerHTML = " Too Short";
val = false;
}
}
}
//Password Validation ----------------------------------------------->
if (isEmpty(register1.password1.value)) {
document.getElementById("Password1Msg").innerHTML = " Empty";
val = false;
}
else {
if (isValid(register1.password.value)) {
document.getElementById("Password1Msg").innerHTML = " Invalid";
}
else {
if (register1.password.value == register1.password1.value) {
if (signup.password1.value.length < 6 && signup.password1.value != "") {
document.getElementById("pass1msg").innerHTML = " Too Short";
val = false;
}
}
else {
document.getElementById("pass1msg").innerHTML = " Don't Match";
val = false;
}
}
}
//Email Validation -------------------------------------->
var EmailField = document.forms["register1"]["email"].value;
var atpos = EmailField.indexOf("#");
var dotpos = EmailField.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EmailField.length) {
document.getElementById("emailmsg").innerHTML = " Invalid Email";
val = false;
}
if (EmailField == null || EmailField == "") {
document.getElementById("emailmsg").innerHTML = " Empty";
val = false;
}
//Main Login Validation Function -->
function validateLoginForm() {
resetMsg();
var val = true;
//Username Validation
if (isEmpty(log_in.username.value)) {
document.getElementById("usernamemsg").innerHTML = " Empty";
val = false;
}
//Password Validation
if (isEmpty(log_in.password.value)) {
document.getElementById("passwordmsg").innerHTML = " Empty";
val = false;
}
return val;
}
</script>
The validations won't work and I dont know why. This is a school project.
my main problem is that the script isnt running when im submiting the form ,when there even some errors at the form(what the user submits) it still goes to the next page and no innerHtml massage is shown.
Here, I went through your code, refractored a lot of it, wrote out some comments on how to improve it.
What stops the form from submitting is returning false. You're returning a variable called val, and if there is an error that variable is set to false, thus returning false and preventing the form from submitting.
I recommend taking the JS and putting it in your text editor and reading through everything. You should learn a good bit.
Here it is: http://jsfiddle.net/2x5LU/
I just did first name cause I have to work now, but you should be able to work off of this.
function validateForm(){
resetMsg();
var val = true;
if(isEmpty(firstName.value)){
firstNameMsg = 'Empty';
val = false;
}else if(isNumeric(firstName.value)){
firstNameMsg = 'Letters Only';
val = false;
}else if(isShort(firstName.value)){
firstNameMsg = 'Too Short';
val = false;
}
return val;
}

How to make a JavaScript form validation that displays an error message simultaneously

Am a new JavaScript programmer and am trying to make a form validator using JavaScript but the error messages don't seem to be displaying if all the forms are not filled, that is if all are empty, only the name form error displays.
This is what I tried:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
if (x == "null" || x == "") {
var b = document.getElementById("nameErr");
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
var b = document.getElementById("nameErr");
b.innerHTML = "";
return true;
}
if (y == "null" || y == "") {
var c = document.getElementById("countryErr");
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
var c = document.getElementById("countryErr");
c.innerHTML = "";
return true;
}
if (z == "null" || z == "") {
var d = document.getElementById("occupationErr");
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
var d = document.getElementById("occupationErr");
d.innerHTML = "";
return true;
}
if (a == "null" || a == "") {
var e = document.getElementById("statusErr");
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
var e = document.getElementById("statusErr");
e.innerHTML = "";
return true;
}
}
This is the JavaScript code.
<form action="process.php" method="post" onsubmit="return myValidate()" name="myform">
Name:
<input type="text" id="name" name="name">
<span id="nameErr"></span><br><br>
Country:
<input type="text" id="country" name="country">
<span id="countryErr"></span><br><br>
Occupation:
<input type="text" id="occupation" name="occupation">
<span id="occupationErr"></span><br><br>
Status:
<input type="text" id="status" name="status">
<span id="statusErr"></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
This is the HTML form.
Please help, Thanks
It seems you don't realize that calling return ends the function you are in. If the validation fails, you'll want to return false, but you do not want to return true until the end of the validation process.
Try:
function myValidate() {
var x = document.forms["myform"]["name"].value;
var y = document.forms["myform"]["country"].value;
var z = document.forms["myform"]["occupation"].value;
var a = document.forms["myform"]["status"].value;
var b = document.getElementById("nameErr");
var c = document.getElementById("countryErr");
var d = document.getElementById("occupationErr");
var e = document.getElementById("statusErr");
if (!x || x.length==0) {
b.innerHTML = "Name Must Be Filled Out";
return false;
} else {
b.innerHTML = "";
}
if (!y || y.length==0) {
c.innerHTML = "Country Must Be Filled Out";
return false;
} else {
c.innerHTML = "";
}
if (!z || z.length==0) {
d.innerHTML = "Occupation Must Be Filled Out";
return false;
} else {
d.innerHTML = "";
}
if (!a || a.length==0) {
e.innerHTML = "Status Must Be Filled Out";
return false;
} else {
e.innerHTML = "";
}
return true;
}
This will return the first error it comes across. If you want to check them all at once, you will need to store your true/false in a variable and hold off on any return calls until then end and call return theVariableName;
you can use a flag for save state :
http://jsfiddle.net/vEvT2/1/
var flag = true;
and change to false if find empty control

Why is the form still submitted?

I wonder why is the form still submitted instead of show the validation results. I have tried also having an onclick event at input type line but also no joy :-(
This is the form
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1"/>
<title>Submit a runner time</title>
</head>
<body>
<script src="TMA02validationSubmitResultForm.js"></script>
<hr/>
<h1>Submit a runner time</h1>
<hr/>
Note: all fields marked '*' are mandatory.
<p/>
<form action="http://jdm423.tt284.open.ac.uk/uploadblock2/storedata.php" method="post" onsubmit="return validateForm()" id="submitrunnertime" name="submitrunnertime">
<table>
<div id="error"> </div>
<tr><td>Runner ID*</td>
<td><input type="text" onblur="validateRunnerId()" id="RunnerId" name="RunnerId" size="5" maxlength="5"/></td>
</tr>
<tr><td>Event ID*</td>
<td><input type="text" onblur="validateEventId()" name="EventId" id="EventId" size="5" maxlength="5"/></td>
</tr>
<tr><td>Date (YYYY-MM-DD)*</td>
<td><input type="text" onblur="validateDate()" name="Date" id="When" size="10" maxlength="10"/></td>
</tr>
<tr><td>Finish time (HH:MM:SS)*</td>
<td><input type="text" onblur="validateTime()" name="FinishTime" id="Time" size="8" maxlength="8"/></td>
</tr>
<tr><td>Position*</td>
<td><input type="text" onblur="validatePosition()" name="Position" id="Position" size="5" maxlength="5"/></td>
</tr>
<tr><td>Category ID*</td>
<td><input type="text" onblur="validateCategoryId()"name="CategoryId" id="CategoryId" size="2" maxlength="3"/></td>
</tr>
<tr><td>Age grade*</td>
<td><input type="text" onblur="validateAge()" name="AgeGrade" id="Age" size="5" maxlength="5"/></td>
</tr>
<tr><td>Personal best</td>
<td><input type="text" onblur="validatePB()" name="PB" id="PB" size="1" maxlength="1"/></td>
</tr>
</table>
<input type="submit" name="submitrunnertime" id="submitrunnertime" value="submit"/>
<hr/>
</form>
</body>
</html>
and the JS
function validateForm() {
return (validateRunnerId
&& validateEventId
&& validateDate
&& validateTime
&& validatePosition
&& validateCategoryId
&& validateAge
&& validatePB);
}
function validateRunnerId(ID) {
var ID = document.getElementById('RunnerId').value;
var legalEntry = /^\d{1,5}?$/;
if (ID.length == 0) {
RunnerId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The RunnerId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
RunnerId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The RunnerId must be a number from 1 to 99999";
return false;
}
else {
RunnerId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateEventId(ID) {
var ID = document.getElementById('EventId').value;
var legalEntry = /^\d{1,5}?$/;
if (ID.length == 0) {
EventId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The EventId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
EventId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The EventId must be a number from 1 to 99999";
return false;
}
else {
EventId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateDate(ymd) {
var ymd = document.getElementById('When').value;
var legalEntry = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
if (ymd.length == 0) {
When.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The date can\'t be empty";
return false;
}
else if (!legalEntry.test(ymd)) {
When.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The date must be in format YYYY-MM-DD";
return false;
}
else {
When.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateTime(tm) {
var tm = document.getElementById('Time').value;
var legalEntry = /^\d\d\:[0-5][0-9]\:[0-5][0-9]$/
if (tm.length == 0) {
Time.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The finish time can\'t be empty";
return false;
}
else if (!legalEntry.test(tm)) {
Time.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The finish time must be in format HH:MM:SS";
return false;
}
else {
Time.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validatePosition(pos) {
var pos = document.getElementById('Position').value;
var legalEntry = /^\d{1,5}?$/
if (pos.length == 0) {
Position.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The position can\'t be empty";
return false;
}
else if (!legalEntry.test(pos)) {
Position.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The position must be a number from 1 to 99999";
return false;
}
else {
Position.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateCategoryId(ID) {
var ID = document.getElementById('CategoryId').value;
var legalEntry = /^\d\d?[0]?$/;
if (ID.length == 0) {
CategoryId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The CategoryId can\'t be empty";
return false;
}
else if (!legalEntry.test(ID)) {
CategoryId.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The CategoryId must be a number from 1 to 100";
return false;
}
else {
CategoryId.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validateAge(agrade) {
var agrade = document.getElementById('Age').value;
var legalEntry = /^\d\d?\,?\d?\d?$/;
if (agrade.length == 0) {
Age.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The age grade can\'t be empty";
return false;
}
else if (!legalEntry.test(agrade)) {
Age.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The age grade must be decimal number of maximum 2 integers and 2 decimals";
return false;
}
else {
Age.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
function validatePB(pbest) {
var pbest = document.getElementById('PB').value;
var legalEntry = /^(0|1)$/;
if (pbest.length == 0) {
pbest.value = "0";
}
else if (!legalEntry.test(pbest)) {
PB.style.background = 'Orange';
error.style.color = 'red';
document.getElementById('error').innerHTML = "The PB can only be 0 for false and 1 for true";
return false;
}
else {
PB.style.background = 'White';
document.getElementById('error').innerHTML = "";
return true;
}
}
Many thanks in advance for taking the time to help this rookie :)
In this code:
function validateForm() {
return (validateRunnerId
&& validateEventId
&& validateDate
&& validateTime
&& validatePosition
&& validateCategoryId
&& validateAge
&& validatePB);
}
...you're not calling your functions, you're just referring to them. And since a function reference is truthy, that condition is always true and the form is always valid.
To call a function, you put () after it. Assuming your functions don't need arguments, that would just be:
function validateForm() {
return (validateRunnerId()
&& validateEventId()
&& validateDate()
&& validateTime()
&& validatePosition()
&& validateCategoryId()
&& validateAge()
&& validatePB());
}
It's hard to tell, though, because a lot of your functions declare arguments but then also declare the same symbol as variables, which is odd to put it mildly.

Categories