How would i validate a text field in html using javascript? - javascript

I have a text field for a user to enter and examination number which is 4 digits long. How would I validate the text field to make sure the digits entered are exactly 4 digits (including a leading 0).
So far I have validated it so that it isn't left blank.
Here's my Javascript:
function validateForm()
{
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.ExamNo.value=="")
{
msg+="You must enter your Examination number \n";
document.ExamEntry.ExamNo.focus();
document.getElementById('ExamNo').style.color="red";
result = false;
}
if(msg=="")
{
return result;
}
{
alert(msg)
return result;
}
}
Here's My html :
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
</tr>
<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>
<tr>
<td id="ExamNo">Examination number</td>
<td><input type="text" name="ExamNo"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>

/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value)
It returns a boolean that check if ExamNo matches that regular expression (4-digit string).
Complete example:
if (!/^\d\d\d\d$/.test(document.ExamEntry.ExamNo.value))
{
msg+="Examination number should be 4-digit number. \n";
document.ExamEntry.ExamNo.focus();
document.getElementById('ExamNo').style.color="red";
result = false;
}

Please see the below link
http://jqueryvalidation.org/documentation/
http://jqueryvalidation.org/files/demo/
This is a validation plugin and easy to use.

Related

Button can't be enabled

My button can't be enabled after having 2 inputs in my textbox not sure how to do this. My button is <input id="rand" type="submit" value="submit" disabled> . I think that its because of the disabled that my entire function is not working... but I don't know any other way to enable it
<script>
function validate()
{
var values = document.getElementById("digit").value;
if(values<0)
{
document.getElementById("numbers").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values && values >= 0)|| values.trim() == "")
{
document.getElementById("numbers").innerHTML = "Fill in a number";
return false;
}
else if (values>=0)
{
document.getElementById("numbers").innerHTML = "";
}
var values1 = document.getElementById("digit1").value;
if(values1<0)
{
document.getElementById("numbers1").innerHTML = "This is not a number, number must be greater or equal to zero"
return false
}
else if (!(typeof +values1 && values1 >= 0)|| values1.trim() == "")
{
document.getElementById("numbers1").innerHTML = "Fill in a number";
return false;
}
else if (values >= values1)
{
document.getElementById("numbers1").innerHTML = "Highest number is smaller than lowest number";
return false;
}
else if (values1 > values)
{
document.getElementById("numbers1").innerHTML = "";
}
if((document.getElementById("digit").value>0) && (document.getElementById("digit1").value>0))
{
document.getElementById("rand").removeAttribute('disabled');
}
else
{
document.getElementById("rand").setAttribute('disabled', 'disabled');
}
}
</script>
This is my codes from my
<body>
<table style="border-collapse: collapse" width="100%">
<form action="random" method="get" onSubmit="return validate()">
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber">
<span id="numbers1"></span>
</td>
</tr>
<tr>
<td>
<input id="rand" type="submit" value="submit" disabled><br/>
<input id="randno" type="text"><br/>
</td>
</tr>
<tr>
<td>
<input id="guess" type="text"><br/>
<input id="guessbut" type="button" value="" >
</td>
</tr>
<br/>
</form>
</table>
</body>
You're enabling the button the right way, by using removeAttribute('disabled'). Maybe you just made some logic error, so you don't reach the removeAttribute statement. Check it out by using console.log()
I think everything works well, except one "u never call your javascript!!".
your js code is wrapped in validate() function and u never call it so it wont be ran forever.
u can try call it using
onchange="validate()"
in your input
so this what it will look like
<tr>
<td>
Lowest number:
<input id="digit" type="text" name="lowestnumber" onchange="validate()">
<span id="numbers"></span>
<br/>
</td>
</tr>
<tr>
<td>
Highest number:
<input id="digit1" type="text" name="highestnumber" onchange="validate()">
<span id="numbers1"></span>
</td>
</tr>
I am not an experienced coder but from what I am reading here is that you are trying to validate an input form and based on that you then disable/enable an input field.
First it is best when validating an input form using regex validations instead of conditionals. Then as soon as the regex is true then you would have to parseInt() which converts the input string to a number (since all inputs are type of string). Then you can make the comparisons.
I've broken down the validations in three stages for you to understand, I know it is a bit messy code but everything depends on the implementation. First validation checks the input with a regex then the second validation checks if the number with the first field and the third validation checks if there is any message/text. If there is no text then all is good so the Rad input field is enabled.
function firstValidation(valueToTest) {
// Your regex matches positive numbers only
var yourRegex = /^[+]?\d+([.]\d+)?$/;
// Test the regex, if false then return the message
return yourRegex.test(valueToTest) ?
"" :
"<br/>Input a number, the number must be greater or equal to zero";
}
function secondValidation(firstInput, secondInput) {
return parseInt(firstInput) < parseInt(secondInput) ?
"<br>Highest number is smaller than lowest number" :
"";
}
function thirdValidation() {
var randField = document.getElementById("rand");
var highestMessage = document.getElementById("message-highestnumber")
.innerHTML;
var lowestMessage = document.getElementById("message-lowestnumber").innerHTML;
// If highestMessage or LowestMessage have no message then everything is ok
randField.disabled = highestMessage || lowestMessage;
}
function validate(inputField) {
var message = firstValidation(inputField.value);
var lowestNumber = document.getElementById("lowestnumber");
var highestNumber = document.getElementById("highestnumber");
// Is the Input field the highest number? Then make the extra check
if (inputField === highestNumber)
message += secondValidation(highestNumber.value, lowestNumber.value);
// After all the checks display the message nextElementSibling will automatically go to the next element which is a span
inputField.nextElementSibling.innerHTML = message;
thirdValidation();
}
<body>
<table>
<tr>
<td>
Lowest number:
<input id="lowestnumber" type="text" name="lowestnumber" onchange="validate(this)">
<span id="message-lowestnumber"></span>
</tr>
</td>
<tr>
<td>
Highest number:
<input id="highestnumber" type="text" name="highestnumber" onchange="validate(this)">
<span id="message-highestnumber"></span>
</td>
</tr>
<tr>
<td>
Rand
<input id="rand" type="text" name="rand"><br />
<span id="message-rand"></span></td>
</tr>
</table>
</body>
Again I might complicate things but everything is based on what implementation you do.

Javascript: validating form fields by regular expression and using if/else statement

In my program I have created form and fields in form. I am trying to validate fields. For that I have used regular expression though my regular expression is correct but regular expression for phone doesn't execute. Can anyone tell me wether I defined if/else statement for validation correctly ?
code:
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "") {
window.alert("Please enter email Address.");
state.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if (phone.value.match(regEx)) {
return true;
} else {
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
}
<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28" /></td>
</tr>
<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"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /> </td>
</tr>
</table>
The problem is here -
if (zip.value.match(regEx2)) {
return true;
} else {
window.alert("Please provide a zip in the ##### or #####-#### format.");
zip.focus();
return false;
}
You are returning from this point regardless of valid or invalid zip. Code blocks afterward won't get executed.
I would suggest not to return in every successful if block, because, the code execution will return from that point without validating the other fields.
function validateForm() {
var valid = true;
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
valid = false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
valid = false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
valid = false;
}
return valid;
}
if you really want to validate one field only when all the previous fields are valid (as your current code), this is working -
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = \^[0-9]{5}(?:-[0-9]{4})?$\;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = \^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$\;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
Here is the complete script -
<!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">Zip</td>
<td><input type="text" name="zip" maxlength="15" size="28"/></td>
</tr>
<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"> EMail </td>
<td> <input type="text" name="email" size="28" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<script>
function validateForm() {
var zip = document.myform.zip;
var email = document.myform.email;
var phone = document.myform.phone;
if (email.value == "")
{
window.alert("Please enter email Address.");
email.focus();
return false;
}
var regEx2 = /^[0-9]{5}(?:-[0-9]{4})?$/;
if(!zip.value.match(regEx2))
{
window.alert( "Please provide a zip in the ##### or #####-#### format." );
zip.focus() ;
return false;
}
var regEx = /^(?:\(\d{3}\)\s|\d{3}-)\d{3}-\d{4}$/;
if(!phone.value.match(regEx))
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
phone.focus();
return false;
}
return true;
}
</script>
</body>
</html>

Javascript function change text colour

So I am creating an exam entry form for school and when a user enters anything wrong, the name of the field will turn red (what the user has input will remain the same) I need to be able to do this with an onclick event activated by my reset button however the function I have right now does not do this. Here is my code:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
if(result) document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
if(result) document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+="You must enter the exam number \n";
if(result) document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
if (document.ExamEntry.examnumber.value.length!=4) {
msg+="Your exam number must be exactly 4 digits \n";
if(result) document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
if(msg != ""){
alert(msg);
return result;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null) {
alert('Please choose an option');
return false;
}
else {
return confirm('You have chosen '+checked.value+' is this correct?');
}
function resetNames() {
document.getElementById('name').removeAttribute('style')
document.getElementById('subject').removeAttribute('style')
document.getElementById('examnumber').removeAttribute('style')
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" placeholder='Name' /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" placeholder='Subject' /></td>
</tr>
<tr>
<td id="examnumber">Exam Number</td>
<td><input type="text" name="examnumber" size="4" maxlength="4" placeholder='No.'/></td>
</tr>
<tr>
<td><input type="radio" id="examtypeGCSE" name="examtype" value="GCSE" /> : GCSE<br/>
<input type="radio" id="examtypeA2" name="examtype" value="A2" /> : A2<br/>
<input type="radio" id="examtypeAS" name="examtype" value="AS"/> : AS<br/>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="return resetNames();" /></td>
</tr>
</table>
</form>
</body>
</html>
I think your closing braces may be in the wrong place... move one of the two closing braces at the end of your JavaScript to the end of the validateForm() function.
try something like this
YOUR CODE
function validateForm() {
....
function resetNames() {
document.getElementById('name').removeAttribute('style')
document.getElementById('subject').removeAttribute('style')
document.getElementById('examnumber').removeAttribute('style')
}
}
CHANGE TO
function validateForm() {
......
}
function resetNames() {
document.getElementById('name').removeAttribute('style')
document.getElementById('subject').removeAttribute('style')
document.getElementById('examnumber').removeAttribute('style')
}
Reason you have nested your function one inside another.

Radio button validation (alert box) confirmation and rejection

I'm working on a HTML document which is an exam submission form. I've completed almost all of the set tasks however, I'm having trouble validating radio buttons. I've searched on stackoverflow however, the answers do not meet the criteria of the question. My completed code is shown below.
I'm having trouble with the bold part of this task:
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Below is the code working, excluding the validation of the radio buttons. Seperatley, I have the code which doesn't work when implemented into the function validateForm().
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
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.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value.length!== 4) {
msg+="Your Examination Number should be 4 digits.\n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<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>
<tr>
<td id="examinationno">Examination Number</td>
<td>
<input type="text" name="examno" />
</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="GCSE" />GCSE</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="AS" />AS</td>
</tr>
<tr>
<td>
<input type="radio" name="examtype" value="A2" />A2</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Submit" onClick="return validateForm();" />
</td>
<td>
<input type="reset" name="Reset" value="Reset" />
</td>
</tr>
</table>
</form>
Based on the current code, why won't the following validate when added into the function?:
if(document.getElementById('GCSE').checked)
{examtype = "GCSE";
}
if(document.getElementById('AS').checked)
{examtype = "AS";
}
if(document.getElementById('A2').checked)
{examtype = "A2";
}
if(confirm("You have selected"+examtype+.Continue?")){
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
else{
alert("Action cancelled");
return false;
}
// Retrieving the checked radio button value
function getRadioValue (frmName, rbGroupName)
{
var radios = document[frmName].elements[rbGroupName];
for (var i=0; i <radios.length; i++)
{
if (radios[i].checked)
{
return radios[i].value;
}
}
return false;
}
Call the getRadioValue() inside validateForm()
// examtype gets false or GCSE or AS or A2
var examtype = getRadioValue ("ExamEntry", "examtype");
"Continue" is a keyword. So you have to wrap it in apostrophes("). I could not get the structure of if-statements, I made some changes. I hope this is what you are looking for..
if(confirm("You have selected"+examtype+". Continue?")){
if(msg==""){
alert(msg);
return result;
}
else{
alert("Action cancelled");
return false;
}
}

I wish to make my code validate a field to make sure it is a number of four digits. How can I do this?

I am currently doing a GCSE course which allows me to ask for assistance from IT sources as long as I reference them in my investigation. I wish to make the following code validate that there is a number of four digits in the Examination Number entry field. I'm okay with simple validation but this is another step for me.
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
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.examnumber.value=="") {
msg+="You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color="red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('examtype');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
document.getElementById('examtype').style.color="red";
}
}
if(checked==null)
{
msg+="Please choose an option";
result = false;
}
else{
confirm("You have chosen "+checked.value+" is this the correct course?");
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /> </td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
Regarding checking if it is number, you can use some regex:
e.g.
var reg = /^\d{4}$/ig;
var regExRes = reg.exec(document.ExamEntry.examnumber.value);
if (document.ExamEntry.examnumber.value == "" || (regExRes == null || regExRes.length == 0)) {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examnumber.focus();
document.getElementById('examnumber').style.color = "red";
result = false;
}
To avoid entering anything beside number, I would suggest you to use something like jquery pluging called masked input
EDIT:
line changed from var reg = /\d{4}/ig; to var reg = /^\d{4}$/ig;

Categories

Resources