Checking if integer JavaScript forms - javascript

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>

You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

Related

if contact number is both empty and does not have 11 digits

id like my "Invalid contact number" to show if the text field is empty or if it does not contain 11 digits (if the text field has content)
HTML:
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
Javascript:
var contact = document.getElementById("contact").value;
if (!contact || (contact.val().length >=12 || contact.val().length <=10) ) {
document.getElementById("number_label").innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
} else {
document.getElementById("number_label").innerHTML = "Contact Number";
}
My "number_label" id in the if statement should change text and display the error.
It isn't working
You're calling .val() on contact (a String) which is no good. .val() is a jQuery method, and is meant to be called on the element itself.
the form just loads the "Invalid contact number" and reloads the page going back to the beginning
If you're trying to restrict a form from posting, make sure any path in your function that should restrict this has a return false.
var label = document.getElementById("number_label");
function validate() {
var contact = document.getElementById("contact").value;
if (!contact || contact.length !== 11) {
label.innerHTML = "<span style='color: red;'>Invalid contact number (must contain 11 digits)</span>";
return false;
} else {
label.innerHTML = "<b>Contact Number</b>";
}
}
<label id="number_label">
<b>Contact Number</b>
</label>
<input type="text" placeholder="Contact Number" class="form-control" id="contact" name="contact">
<button onclick="validate()">Validate</button>
Your code has some errors. val() is not a function of the element.
if (!contact || (contact.**val()**.length >=12 || contact.**val()**.length <=10) ) {
Follows a fiddle with the code fixed. link

JavaScript-form validation

I am doing some form validation in JSP, on click on submit button "validate_access()" function is not called or not working. Sometimes this function displays a alret box and then stop doing any thing . Please tell what is wrong with this piece of code.Here is a piece of code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Data management system</title>
<script language="JavaScript" type="text/javascript">
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(document.myform1.MISDN.value=="" && document.myform1.Issue.value=="" && document.myform1.SR.value=="" && document.myform1.date.value=="")
{
alert("Manadotry fields should not left blank");
document.myform1.MISDN.focus();
document.myform1.Issue.focus();
document.myform1.SR.focus();
document.myform1.date.focus();
return false;
}
else if(!a.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.MISDN.focus();
return false;
}
else if(!(b.value.match(numbers) && b.value.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myform1.Issue.focus();
return false;
}
else if(!c.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.SR.focus();
return false;
}
else if(!d.value.match(Datee))
{
alert('Please input correct date');
document.myform1.date.focus();
return false;
}
else
return true;
}
</script>
</head>
<body>
<div class="main">
<div class="header"></div>
<div class="continer">
<div class="myform1" style="height:200px; width:300px; float:left;">
<h2>1344 Access</h2>
<form name="myform1" action="access.jsp" method="get" onsubmit="return validate_access()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>Issue:<input type="text" name="Issue" maxlength="13">
<br/>SR:<input type="text" name="SR">
<br/>Date:<input type="text" name="date" value="dd/mm/yy">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
<div class="myform2" style="float:left;height:200px; width:300px;">
<h2>O.C.S</h2>
<form name="myform2" action="ocs.jsp" method="post" onsubmit="return validate_ocs()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>SR:<input type="text" name="SR">
<br/>REASON:<input type="text" name="reason">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
</div>
</div>
</body>
Problems in your javascript are:
the first if condition check is wrong you mean || in place of &&.
then next when you call match method on empty string a error probably raise like:
Uncaught TypeError: Cannot read property 'match' of undefined
you calling .focus() continuously that doesn't making any sense, call once with a condition check.
There is something wrong in this line:var a = document.forms["myForm1"]["MISDN"].value;
Look at your source code, your form name is "myform1" not "myForm1".
JavaScript is case sensitive.
http://en.wikipedia.org/wiki/JavaScript_syntax
in your js:
document.forms["myForm1"]
but in your form(html) it is:
<form name="myform1"
Try this:
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(a == "" && b == "" && c == "" && d == "")
{ //as you have default value for d (date field), this condition will never match;
//either you can remove default value or provide different logic
alert("Manadotry fields should not left blank");
document.myForm1.MISDN.focus();
document.myForm1.Issue.focus();
document.myForm1.SR.focus();
document.myForm1.date.focus();
return false;
}
else if(a == "" && !a.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.MISDN.focus();
return false;
}
else if(!(b.match(numbers) && b.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myForm1.Issue.focus();
return false;
}
else if(!c.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.SR.focus();
return false;
}
else if(!d.match(Datee))
{
alert('Please input correct date');
document.myForm1.date.focus();
return false;
}
else
return true;
}
Your mistakes:
(i) form name spelling mistake (caseSensitive)
(ii) you used HTMLElement.value.value to check (in if conditions)
For example:
var a = document.forms["myForm1"]["MISDN"].value;
a.value.match(numbers); // it simply means HTMLElement.value.value (which will never work)

All Browsers seem to ignore JavaScript Client Side form validation rule

I've used JavaScript to ensure that the fields on my form are correctly filled out (required fields with correct type of information) and the browser seems to ignore the rules I set and process the information anyway.
HTML
HTML
<form id="course-form" name="courseForm" method="POST" onSubmit="return checkCourse()" action="#">
<label for="courseName">Course Name: </label>
<input type="text" id="course-name" name="courseName" placeholder="Course Name" required/><br/>
<br>
<label for="qualDesc">Description: </label><br/>
<textarea name="qualDesc" class="boxsizingBorder" placehold
<label for="entryReqs">Entry Requirements</label><br>
<textarea name="entryReqs" class="boxsizingBorder" id="entry-reqs" placeholder="Previous Grades Required" required></textarea><br>
<br>
<label for="cost">Cost: £</label>
<input type="text" name="cost" id="courseCost" maxlength="6" size="5" required/><br>
<br>
<input type="submit" value="Add Course" />
</form>
JavaScript(Placed in Head of document)
<script>
function checkCourse()
{
var date = new Date();
var year = (date.getFullYear());
var courseName=document.forms["courseForm"]["courseName"].value;
var courseDesc=document.forms["courseForm"]["qualDesc"].value;
var courseYear=document.forms["courseForm"]["year"].value;
var entryReqs=document.forms["courseForm"]["entryReqs"].value;
var cost=document.forms["courseForm"]["cost"].value;
if(courseName == "")
{
alert("Course name is a required field.");
return false;
}
else if(courseDesc=="")
{
alert("The Course needs a description");
return false;
}
else if(courseYear < year)
{
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);
return false;
}
else if(entryReqs=="")
{
alert("You must enter some entry requirements");
return false;
}
else if(isNaN(cost) || (cost==""))
{
alert("Cost is not a valid numerical figure");
}
alert("Course added sucessfully!");
return true;
}
</script>
**Note, I've also tried putting the return true section in an else statement like this:
else
{
alert("Course added sucessfully!");
return true;
}
Am I missing something?
Thanks
In the line below, you try to get the value of an input, but your form does not contain an input that is named year. This will cause a Javascript error and subsequently, your validation will be disregarded and the form will continue to submit
var courseYear=document.forms["courseForm"]["year"].value;
A second problem is you don't return false if the cost validation fails (but this is not your root problem).
Also as juvian points out, you are missing a closing quote on the alert below:
alert("The academic year for " + courseYear + " has already commenced. \n Please pick a later date);

How to check if the user has not entered the data to a form (befor sending)?

I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you

How do I disable form dropdown option using javascript

I'm trying to disable the "name" text field in the form when "Choose" is selected in the drop down after the page loads (it's disabled when the page loads) ie after I've chosen one of the other two options that disable or enable that field, when I return to "Choose" i'd like the same field to disable. I can't see why the javascript I've written would prevent this from happening. Thanks!
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value === defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value === "") {
thisfield.value = defaulttext;
}
}
function checkPickup() {
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
/* Reset form values */
form.name.value = "His/her name";
}
}
</script>
<script type="text/javascript">
function validate(form) {
var errmsg = "Oops, you're required to complete the following fields! \n";
// Various other form validations here
// Validate "Pickup"
if (form.os0.value === "") {
errmsg = errmsg + " - Choose pickup or delivery\n";
}
// Validate "phone"
if (form.phone.value === "" || form.phone.value === "Mobile's best!") {
errmsg = errmsg + " - Your phone number\n";
}
if (form.os0.value != "Pickup from Toowong, Brisbane") {
// Validate "name"
if (form.name.value === "" || form.name.value === "His/her name") {
errmsg = errmsg + " - His/her name\n";
}
}
// Alert if fields are empty and cancel form submit
if (errmsg === "Oops, you're required to complete the following fields! \n") {
form.submit();
} else {
alert(errmsg);
return false;
}
}
</script>
</head>
<body>
<form name="form" action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return validate(form)">
<p class="row">
<input type="hidden" name="on0" value="Pickup and delivery" />Pickup and delivery<br />
<select name="os0" onchange="checkPickup()">
<option value="" selected >Choose</option>
<option value="Pickup from Toowong, Brisbane">Pickup from Toowong, Brisbane $1.00 AUD</option>
<option value="Brisbane +$23.60">Brisbane +$23.60 =$1.00 AUD</option>
</select>
</p>
<p class="row">Your daytime phone number<br />
<input type="text" name="phone" value="Mobile's best!" onclick="clickclear(this, 'Mobile\'s best!')" onblur="clickrecall(this,'Mobile\'s best!')" />
</p>
<p class="row">Recipient's name<br />
<input style="color: #ccc" class="name" type="text" name="name" value="His/her name" onclick="clickclear(this, 'His/her name')" onblur="clickrecall(this,'His/her name')" disabled />
</p>
<input name="custom" type="hidden" />
<input type="hidden" name="currency_code" value="AUD" />
<input class="button" type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1"> -->
</form>
</body>
</html>
This may be a simple misunderstanding of what you've written:
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
translates to the following in plain english:
If the value is NOT "Pickup from Toowong, Brisbane", enable the field, otherwise disable it.
which is equivalent to:
ONLY disable the field when the value is "Pickup from Toowong, Brisbane".
I believe the logic you're looking for is:
if (form.os0.value == "Brisbane +$23.60" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
though it might be prettier to code this with a switch statement due to the involvement of specific cases.
See DEMO
did you intend to type double equal to (==) or is the triple equal to (===) a typo in the question? Based on looking at your code, it looks to me like you need a double equal to (==) not a triple. I think triple may mean something else.

Categories