JavaScript Form, with validation - javascript

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. So far, i have the 'name', 'subject' and 'Examination number'. However my validation does not work for my Examination number. for examination number, i want the validation to make sure that the input is only 4 digits, hence i added 'maxlength="4"'. If someone could please help me with this validation to firstly validate the examination number and ensure that the input is four digits, it would be very helpful, thanks
here is my code:
<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;
}
if (document.ExamEntry.Examination_number.value=="4") {
msg+="You must enter your Examination number \n";
document.ExamEntry.Examination_number.focus();
document.getElementById('Examination_number').style.color="red";
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><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

it's not .value == "4" it's .value.length == 4

You can actually use html5 for this, no javascript required!
Along with the maxlength attribute, include this attribute:
pattern="\d{4}"
the "pattern" attribute allows you to specify a regex pattern for validating the input.
\d is regex meaning "digits". {4} is regex meaning repeat exactly 4 times.
The maxlength attribute is actually redundant now, and can be removed since the regex will limit the length of the input on its own.
So overall, your element can look like:
<input type="text" pattern="\d{4}" name="Examination_number" />
Also just one note: It's also important to keep in mind that client side validation is not equivalent to server-side validation. Anyone with basic webdev knowledge will still be able to post invalid Examination_Number values to your server. Your server must be able to validate these values as well.

Use regex... var regex = /^\d{4}$/;
And of course, sorry, you can do it matching the regex... if (regex.test(examinationnumber)) then good..
You could also check the value with isNaN to be sure of getting numbers, like:
if (!isNaN(examinationnumber)) then good..
To make them alltogether:
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;
}

Related

Form Validation doesn't validate for Password

I can't see what's wrong. When I try to validate email it works fine, but it doesn't check for the password at all! It's literally the simplest a program can get.
function validateForm() {
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
if (email == "") {
alert("Email must be filled out");
document.getElementById("emailE").innerHTML = "<font color=\"red\"> Pls fill in email.</font>";
return false;
}
else if (password == "" && password.length > 8) {
alert("Password must be filled out");
document.getElementById("passwordE").innerHTML = "<font color=\"red\"> Pls fill in password and it should be greater than 8 chars.</font>";
return false;
}
}
</script>
</head>
<body>
<h1>School Form</h1>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
<table cellspacing="10">
<tr>
<th>Email:</th>
<th><input type="email" name="email"></th>
<th><span id="emailE"></span></th>
</tr>
<tr>
<th>Password:</th>
<th><input type="password" name="password"></th>
<th><span id="passwordE"></span></th>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>```
You are checking the email and not password because once the first if statement is true it will not go to the else if of the same block so use them in different blocks of if else statement or use both of them in one if statement
secondly you are checking for the length of password is more than 8 and its value is '' so this is impossible to have.
Here are some suggestions
Font tag is depreciated a long ago so don't use this

Javascript: Getting error while validating number using regular expression

I am trying to validate telephone number in this format : (xxx) xxx-xxxx.
For that I have used regular expression but it doesn't validate when I enter incorrect format and click on submit it doesn't show any error. Can anyone help me to identify an issue?
code:
<!DOCTYPE html>
<html>
<head>
<title>NumerValidation</title>
</head>
<body>
<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /> </td>
</tr>
</table>
</form>
<script>
function validateForm() {
var phone = document.myform.phone;
var regPhone = /^\(?[(]?[0-9]{3}[)]?[-\s]?[0-9]{3}[-]?[0-9]{4}$/im;
//var phone = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;
if(phone.value.match(regPhone))
{
return true;
}
else
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
return false;
}
}
</script>
</body>
</html>
use this regular expression
^\(\d{3}\)\s{0,}\d{3}\s{0,}-\s{0,}\d{4}$
it matches
(111)111 - 1111
(111) 111 - 1111
(111) 111- 1111
(111) 111- 1111
(111) 111-1111
(111) 111 - 1111
incase the user adds spaces at the beginning or end of the phone number, you have to trim it with
value = value.trimLeft();
value = value.trimRight();
if you don't trim white spaces at the beginning and end of the input, the regexp will fail even if the user inputs valid number

Validation not working for dynamically created values

I have created a form along with dynamically created form fields (name, age). While trying to validate my age field using javascript, only the first record of the age field is validating - the other ones aren't.
The code is:
<script type="text/javascript">
function formValidator(){
var age = document.getElementById('age');
if(isNumeric(age, "Please enter a valid Age")){
return true;
}
return false;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
HTML code is:
<html>
< body>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</body>
</html>
Only the first field is validating. How can I validate the dynamically generated fields?
You have duplicate IDs for form element. which is targeting only first element matched with ID. You should rather use same class and target all of them for validation. give class age instead of id and then use:
function formValidator(){
var age = document.getElementsByClassName('age');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
If You are using dynamic values then pass dynamic ids to the javascript function and then do the validation
For example :
for(i=0;i<results;i++)
{
<input type="text" size="20" name="age[]" id="age"<?php echo i; ?> >
}
And in the javascript function read all the dynamic ids and do the validation.
The bug is in this line. getElementById returns the DOM element and not its value.
var age = document.getElementById('age');
To get the value in the DOM element, you should use the 'value' attribute.
var age = document.getElementById('age').value;
hope that fixes the issue.
You are getting only one element and create it with duplicated ID's. You should get all elements and check them using a loop.
function formValidator(){
var ageEls = document.getElementsByName('age[]'),
valid = true,
i = 0;
while (i < ageEls.length && valid) {
valid = isNumeric(ageEls[i], "Please enter a valid Age");
i++;
}
return valid;
}
JSFiddler example: http://jsfiddle.net/3zsLhe9c/3/
for jquery i have colustion if you use this "jquery.validate.unobtrusive.js" js.
$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");$("#FrmSubmitToAgent").removeData("validator");
$("#FrmSubmitToAgent").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

JavaScript radio buttons html web 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. For the 'qualification' fields, I have radio buttons where the user has to click-select their qualification. I have the validation in place, but unfortunately I cant get the field to be highlighted in red and display the error message when the form is submitted and the 'qualification' has been left blank. everything works apart from the qualification field. It would be great if someone could fix the validation of the 'qualification' so that when the field is left emty, the text will be highlighted and the error message will be included. thanks
here is my 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.group1.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";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
document.getElementById('Examination_number').style.color="red";
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=”50%” 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>
the return value of the group1 radio buttons when none are selected is undefined, not "" as you expected, so you need to change the condition in the if statement
if (document.ExamEntry.group1.value==undefined)

retype password verification not working

I used the following code:
<script type="text/javascript">
function validate() {
if ((document.changepass.newpassword.value != '') &&
(document.changepass.retypenewpassword.value ==
document.changepass.newpassword.value)){
document.changepass.retypenewpassword.blur();
document.changepass.submit();
}
}
</script>
<form name="changepass" method="POST" action="changepassword.jsp" onsubmit="return validate();">
<table align="center">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" size="20"
style="width: 145px" maxlength="10"></td>
</tr>
<tr>
<td>Retype New Password:</td>
<td><input type="password" name="retypenewpassword" size="20"
style="width: 144px" maxlength="10"></td>
</tr>
<tr>
<td><input type="submit" value="Change Password" name="operation" ></td>
<td><input type="reset"></td>
</tr>
</table>
</form>
but when I'm giving unmatched entry then also it getting changed.i mean the validate function is not getting called.
plz help
in hope
robin
Your form will submit no matter what, because you are not returning false from the validating function on error. It should be:
function validate() {
var d = document.changepass;
if((d.newpassword.value != '') && (d.retypenewpassword.value == d.newpassword.value)) {
return true;
}
return false;
}
At current, you are not specifying a return value for validate(), and it is interpreted as always returning true, so the form gets submitted. You don't need to call submit() from your function, simply return true if everything is ok.
The onsubmit handler on your <form> is looking for a return value, but is not given one from your validate function. Instead of calling submit() in the function, you should return true or false, depending on if the form validates (if the function returns false, that is equivalent to onsubmit="false", which will cancel the submission):
function validate()
{
if ((document.changepass.newpassword.value != '') && (document.changepass.retypenewpassword.value != document.changepass.newpassword.value))
{
// A password is given but it doesn't match
// Perhaps you want to alert() an error message here to tell the user why the form doesn't validate?
return false;
}
return true;
}

Categories