Javascript Validation Not Working When Submitting - javascript

I've been developing my first website, and I'm having issues with a javascript validation script. My code:
<html>
<head>
<title>Territory</title>
</head>
<body>
<script type="text/javascript"> //Main Javascript function giving me issues
function validate(form)
{
fail = validateTerrNum(document.checkOut.numberOut.value);
fail += validateFirstName(document.checkOut.fName.value);
fail += validateLastName(document.checkOut.lName.value);
if (fail == "")
return true;
else
{
alert(fail);
return false;
}
}
</script>
<script type="text/javascript>
function validateTerrNumber(field)
{
if (field == "") return "No territory number was entered. \n";
else if (field.length > 3)
return "Territory numbers must be less than four characters. \n";
else if (/[^0-9]/.test(field))
return "Only 0-9 allowed in territory number. \n";
return "";
}
//Note: Does not sanitize string
function validateFirstName(field)
{
if (field == "") return "No first name was entered. \n";
return "";
}
//Again, note that this function does not sanitize string
function validateLastName(field)
{
if (field == "") return "Not last name was entered. \n";
return "";
}
</script>
<table border="0" cellpadding="2" cellspacing="5">
<th colspan="2" align="center">Check Out</th>
<form name="checkOut" method="post" onSubmit="validate(this)">
<tr><td>Territory Number</td><td><input type="text" name="numberOut" tabindex="1" maxlength="3" size="3" /></td>
</tr><tr><td>First Name of Holder</td><td><input type="text" name="fName" tabindex="2" maxlength="15"/></td>
</tr><tr><td>Last Name of Holder</td><td><input type="text" name="lName" tabindex="3" maxlength="15" /></td>
</tr><tr><td><input type ="checkbox" name="specialC" tabindex="4" value="Yes"/> Special Campaign</td>
</tr><tr><td></td><td><input type="submit" value="Check Out" /></td>
</form>
</table>
</body>
</html>
It is obviously poorly formatted - result of copy and paste. To be more specific, this issue is with the javascript validation. When I hit "Check Out," the validation does not prevent it when I put in bad values. The script is quite simple, but for some reason I can't figure out what is going on with it (I'm fairly new to javascript).
I know the issue is not my browser as I have many javascripts running throughout it. The only thing I can think of is that the form does not have a method. It will be another validation, but written in php - the javascript is really just a prevalidation for the client.
Any help would be appreciated.
-Mlagma

To stop the submit going ahead after validation fails you need:
onSubmit="return validate(this)"
instead of your current code:
onSubmit="validate(this)"
Your validate() function already returns true or false, but those values were not being returned from the event handler itself. If you think of the code between the quotes of onSubmit="" as the body of a function this makes sense.
And, asTeemu pointed out, your validate() function tries to invoke a function called validateTerrNum when actually you've declared that function as validateTerrNumber.
With these problems corrected you can see it working here: http://jsfiddle.net/nnnnnn/Wvcy3/

You have this line in validate():
fail = validateTerrNum(document.checkOut.numberOut.value);
And there is this function:
function validateTerrNumber(field){...
Also document.checkOut is undefined rather than form element (browser dependent???), it's better to use document.getElementById('numberOut').value instead, (same for fName and lName). Ofcourse you'll need to add these ids in the HTML.

Related

The input from client side should entered only digits, if is alphabets should give an error msg

Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {

JavaScript function() is not a function

I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function
The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.

Prevent form from submitting when certain fields are empty

I would appreciate your help on this one. I tried to use code from other questions, but unfortunately it doesn't work.
I am trying to prevent a form from submitting and show an alert ("Select dates so continue")if two specific fields are empty. In this case "checkin" & "checkout"
This is the code for the first input field:
<input type="text" id="checkin" readonly="true" name="checkin" class="form-control search-input" placeholder="Check-in date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"required>
<div class="input-group-addon search-icon-right" onclick="$('#checkin')[0].focus()" onfocus="$('#checkin')[0].focus()">
Code for the second field:
<input type="text" readonly="true" id="checkout" name="checkout" class="form-control search-input" placeholder="Check-out date" data-provide="datepicker-inline" data-date-orientation="bottom" data-date-autoclose="true" data-date-start-date="now" data-date-format="<?php echo $javascriptLocal ?>" data-date-language="<?php echo $language ?>"/>
<div class="input-group-addon search-icon-right" onclick="$('#checkout')[0].focus()" onfocus="$('#checkout')[0].focus()">
I tried to achieve it with this javascript:
<script type="text/javascript">
function empty() {
var x;
x = document.getElementById("checkout").value;
if (x == "") {
alert("Select dates to continue");
return false;
};
}
</script>
However, this does not work. Could your please help me?
EDIT:
This is the Javascript that seems to interfere with my code: Any suggestions?
<script>$(document).ready(function(){$(".gotop").on("click",function(){$("html, body").animate({scrollTop:$("body").offset().top},1000)});$("#child").on("change",function(){var a=$(this).val();if(a<=0){$(".child-age-1-container").fadeOut("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-1").val(0);$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==1){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeOut("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-2").val(0);$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==2){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeOut("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-3").val(0);$("#child-age-4").val(0)}else{if(a==3){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeOut("slow");$("#child-age-4").val(0)}else{if(a>=4){$(".child-age-1-container").fadeIn("slow");$(".child-age-2-container").fadeIn("slow");$(".child-age-3-container").fadeIn("slow");$(".child-age-4-container").fadeIn("slow")}}}}}});$("#checkin").datepicker().on("changeDate",function(){var a=$("#checkin").datepicker("getDate");a.setDate(a.getDate()+2);$("#checkout").datepicker("setDate",a);$("#checkout")[0].focus()});$(".btn-hotel-search").on("click",function(a){a.preventDefault();var j=$("#search-form");var g=$("#child-age-1").val();var f=$("#child-age-2").val();var e=$("#child-age-3").val();var d=$("#child-age-4").val();var b;var c=$("#child").val();var h="";for(b=1;b<=c;b++){h+=$("#child-age-"+b).val()+","}h=h.substr(0,h.length-1);j.append($('<input type="hidden" name="childages">').val(h));j.get(0).submit()})});</script>
Use HTML5 required attribute on the input elements, the form wont be submitted if the fields are empty. to learn more about html5 validation please visit
http://www.the-art-of-web.com/html/html5-form-validation/
You can try like this:
$('form').on("submit",function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
alert('Stopped');
})
Or by button
$('#submitButton').on("click",function(e) {
e.preventDefault();
alert('Stopped');
})
First thing you can do is mark your checkout field as required, jsut like checkin this would help.
Second you can trace your values with temporary alerts while debugging, this helped me a lot when looking for javascript issues.
Third you can try to use a strict comparaison operator and be a bit more specific with the function return values as such
<script type="text/javascript">
function empty() {
var x = document.getElementById("checkin").value;
var y = document.getElementById("checkout").value;
if (x === "" || y === "") {
alert("Select dates to continue");
return false;
};
return true;
}
</script>
You can try something like this in javascript
if(!x){
alert('Stopped');
}
In Javascript every variable can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.
Hope it help
Just change it to
if (!x) {
alert("Select dates so continue");
return false;
}
This will check if variable is null, empty, or undefined
use the "required" attribute for the specific input tag
just give input type="submit" below that
<input type="number"
name="stock"
required
onChange={(e)=>{this.setState({ quantity: e.target.value , number: val.qty})}}/>
<input type="submit" />
WORKS PERFECT!!!

Form is being submitted in IE11

The below form is being submitted even when its txt_approver is empty.
But it works well in firefox/chrome?
I get no error, what could be the issue?
<script>
function validateForm() {
var x = document.forms["warningnotice"]["txt_approver"].value;
alert(x);
if (x == null || x == "") {
alert("Please enter a name to send a email to ");
return false;
}
}
</script>
<form method="post" action="travel.cfm" id="commentForm" name="warningnotice" onsubmit=" return validateForm()">
<td ><input type="text" name="txt_approver" class="get_empl" required data-error="#errNm35"></td>
<input type="submit" name="Submit" value="Submit" >
</form>
You are using the name attribute to locate the form and the textbox in JavaScript. This is not what the name attribute is for. The id attribute is for this.
Instead of:
document.forms["warningnotice"]
and
<input type="text" name="txt_approver" ...
Those lines should be:
document.forms["commentForm"]
and
<input type="text" name="txt_approver" id="txt_approver"...
And, instead of document.forms, use:
var form = document.getElementById("commentForm");
var tb = document.getElementById("txt_approver");
Also, instead of:
if (x == null || x == "")
You can just use:
if (!String.trim(x))
Because an empty textbox will produce an empty string "" and an empty string, converted to a boolean (which an if statement looks for) will be false, but a populated one, will convert to true.
Lastly, you probably don't want to have your submit button have a name attribute at all because when the form is submitted, the value of the submit button will be submitted along with the other form elements, which probably is not what you want.
The following JS Fiddle shows the code that is working for me in IE 11: https://jsfiddle.net/x0rbnL5s/

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

Categories

Resources