Validating age field - javascript

I'm trying to validate an age field in a form but I'm having some problem. First I tried to make sure that the field will not be send empty. I don't know JavaScript so I searched some scripts and adapted them to this:
function isInteger (s)
{
var i;
if (isEmpty(s))
if (isInteger.arguments.length == 1)
return 0;
else
return (isInteger.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (!isDigit(c))
return false;
}
return true;
}
function isEmpty(s)
{
return ((s == null) || (s.length == 0))
}
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if ((validate_required(age,"Age must be filled out!")==false) ||
isInteger(age,"Age must be an int number")==false))
{email.focus();return false;}
}
}
//html part
<form action="doador.php" onsubmit="return validate_form(this)" method="post">
It's working fine for empty fields, but if I type any letters or characters in age field, it'll be sent and saved a 0 in my database. Can anyone help me?
Sorry for any mistake in English, and thanks in advance for your help.

You can use isNaN() to determine if an object is a number, for example:
someString="6";
someNumber=5;
someFloat=3.14;
someOtherString="The";
someObject = new Array();
isNaN(someString); // Returns false
isNaN(someNumber); // Returns false
isNaN(someFloat); // Returns false
isNaN(someOtherString); // Returns true
isNaN(someObject); // Returns true
Then you can use parseFloat() or parseInt() to convert a string into a number:
aString = "4";
aNumber = parseInt(aString);
if(aNumber<5)
alert("You're too young to use this website");
See also this other question that vladv pointed out in the comments.

Related

Conditional javascript input field validation

I am currently working on a project that requires me to do a javascript form validation on a form that contains conditional input fields ( the visitor can choose whether to log in via a user number or email address ). Both input fields are separate and I need to do the following:
If visitor chooses to log in via option A ( user number ), the validation should only take into account the id of input field A ( the user number ) and not require validation for the other field ( email address ).
And vice versa, if visitor chooses option B.
The code I am currently using for validation:
function empty() {
var x;
x = document.getElementById("user_number").value;
if (x == "") {
MsgBox('Your user number is required.', 'ERROR');
return false;
}
var y;
y = document.getElementById("email").value;
if (y == "") {
MsgBox('Your email address is required.', 'ERROR');
return false;
}
}
And the form trigger event:
<form method="POST" id="accordion-top-form" action="" onsubmit="return empty();">
I need to expand the current script to check if either field A or field B has been filled in when submitting the form ( and then automatically disable validation for the other field ).
How do I do that?
You could use the following:
var forms = {
user: 0,
email: 1
};
function whichForm() {
var userForm = document.getElementById("user_number").value;
var emailForm = document.getElementById("email").value;
if (userForm && emailForm) {
//user wrote in both forms, something is wrong
} else if (!userForm && !emailForm) {
//user didn't fill in any form
} else {
return userForm ? forms.user : forms.email;
}
}
function empty(form) {
if (form === forms.user) {
// check if the user number form is empty
var userForm = document.getElementById("user_number").value;
if(userForm.trim() === "") {
// possibly do more validation
// return true or false based on whether you want to submit
}
} else if (form === forms.email) {
// check if the email form is empty
var emailForm = document.getElementById("email").value;
if(emailForm.trim() === "") {
// possibly do more validation
// return true or false based on whether you want to submit
}
} else {
// something is wrong, invalid parameter,
// handle here
return false
}
}
function validate() {
return empty(whichForm());
}
And change your form so that it calls return validate() inline or just validate as a submit handler.
Sounds like this would be enough?
I would personally not call the function empty since you want to return true to allow submission
function empty() {
var x = document.getElementById("user_number").value,
y = document.getElementById("email").value;
x = x?x.trim()|| ""; // handle null and all blanks
y = y?y.trim()|| "";
if (x === "" && y === "") {
alert("Please enter user number or email")
return false;
}
// optional
if (x && y) { // both entered
alert("Please enter EITHER user number or email")
return false;
}
if (x) return isValidUser(x); // each of these functions needs to return boolean
if (y) return isValidEmail(y);
// likely not going to happen
return false;
}
You can test if both are empty
function empty() {
var a = document.getElementById("user_number").value,
b = document.getElementById("email").value;
if ("" == a && "" == b) return MsgBox("Your user number or mibile is required.", "ERROR"), !1
};
Code do it in this way:
function empty() {
var x = document.getElementById("user_number").value,
y = document.getElementById("email").value;
if (!x && !y) {
alert('You should choose email address or number');
return false;
}
return true;
}
Proposed solution:
Check which of the two input fields is filled up:
var inputA = document.getElementById('A').value;
var inputB = document.getElementById('B').value;
if ((inputA !== "") || (inputA !== NaN) || (inputA !== undefined)) {
//execute code for the user number
}
else if ((inputB !== "") || (inputB !== NaN) || (inputB !== undefined)) {
//execute code for the email
}
else {
//display an error saying none of the two fields were used
}
Recommendation: Most websites would only use 1 input because it looks a lot cleaner. And the place holder text can specify to the user what input options he should put in:
<input type="text" id="input1" placeholder="user number or email">
Proposed Solution: Check if the user input has a # symbole:
var input1 = document.getElementById("input1").value;
var emailInput = input1.includes('#');//returns a boolean with a value of true
//if '#' was found in the string input1
if (emailInput) {
//execute the code for the email input
} else {
//execute the code for the userID input
}
Explanation:
I assumed that you wanted to use the same input field inside your <form ...> tag regardless if the user is using an email or an id number to log in. From that, what I saw as most logical is to just find something that is unique to one of those inputs, and base the logic of your code on whether that unique element existed in the input provided.
AKA since emails always have the # symbol, verifying if this exists in the provided string or not should be enough to verify if the user used an email or id number to attempt to login.
Let me know if that helped :).

charAt not evaluating

I am trying to write a function that will evaluate equality of characters in a string and return true if 3 in a row match. The charAt() doesn't seem to be working as the if statement always goes to the else block.
function myFunction(num1)
{
var checkNum1;
for (var i = 0; i < num1.length; i++)
{
if (num1.charAt(i) == num1.charAt(i+1) && num1.charAt(i) == num1.charAt(i+2))
{
checkNum1 = true;
break;
}
}
if (checkNum1 == true)
{
return true;
}
else
{
return false;
}
}
What should I be doing to get the last "if" block to return true?
The code that you have provided works fine with strings ie: myFunction("257986555213") returns true.
However, myFunction(257986555213) returns false as expected as charAt is a String method.
As a fail-safe approach, you can try adding the following line to your method at the beginning:
num1 += '';
This should convert your argument to string and you should get your results..
Hope it Helps!!

JavaScript Throws Undefined Error

What it is supposed to do -
Example
url1(pages,"ALT") returns "www.xyz.ac.uk"
url1(pages,"xyz") returns ""
The error - TypeError: Cannot call method 'toUpperCase' of undefined
This is just for some coursework, Im stuck with these errors. Any help would be much appreciated
function index(string,pattern,caseSensitive) {
if(caseSensitive == false) {
var v = string.toUpperCase();
} else {
var v = string;
}
return indexNumber = v.indexOf(pattern);
}
var pages = [ "|www.lboro.ac.uk|Loughborough University offers degree programmes and world class research.", "!www.xyz.ac.uk!An alternative University" , "%www%Yet another University"];
alert(url1(pages, "ALT"));
function url1(pages,pattern) {
var siteContent = [];
for(i=0;i<pages.length;i++) {
var seperator = pages[i].charAt(0);
if(pages[i].indexOf(seperator)>0){
siteContent = pages[i].split(pages[i].indexOf(seperator));
}
if( index(siteContent[2],pattern,false)>=0){
return siteContent[1];
}else{
return "";
}
}
}
if(pages[i].indexOf(seperator)>0){
siteContent = pages[i].split(pages[i].indexOf(seperator));
}
if( index(siteContent[2],pattern,false)>=0){
return siteContent[1];
}else{
return "";
}
If pages[i].indexOf(seperator)<=0, siteContent is still whatever it was from the last iteration. If that happens on the first iteration, siteContent is still [], and siteContent[2] is undefined.
Another problem: the expression pages[i].indexOf(seperator) returns a number, and pages[i].split expects a delimiting string as an argument. Since the number doesn't appear in your input, you'll always get a single-element array, and siteContent[2] will always be undefined. Get rid of .indexOf(seperator), change it to siteContent = pages[i].split(seperator).
One more: get rid of the else { return ""; }. Add a return ""; after the for loop.
Finally, in the first if statement condition, change .indexOf(seperator) > 0 to .indexOf(seperator, 1) !== -1. Since you're getting seperator from the first character of the string, it will be found at 0. You want the second occurrence, so start the search at 1. In addition, .indexOf returns -1 if it doesn't find the substring. You'll need to account for this in both if conditions.
Side note, as this is not causing your problem: never use == false. JS will coerce stuff like 0 and "" to == false. If that's what you want, just use the ! operator, because the expression has nothing to do with the value false.
My final answer is http://jsfiddle.net/QF237/
Right here:
alert(url1(pages, ALT)); // ALT ISN'T DEFINED
I believe you forgot to quote it:
alert(url1(pages, "ALT"));
You should split the string passing the separator character itself. Your function then will look like:
function url1(pages,pattern) {
var siteContent = [];
for(i=0;i<pages.length;i++) {
var seperator = pages[i].charAt(0);
console.log(seperator);
if(pages[i].indexOf(seperator)>=0){
siteContent = pages[i].split(seperator); //fixed here
}
console.log(siteContent);
if( index(siteContent[2],pattern,false)>=0){
return siteContent[1];
}else{
return "";
}
}
}
Tell us if it worked, please.
EDIT: It seeems your index() also has a little problem. Please try the function below.
function index(string,pattern,caseSensitive) {
var v;
if(caseSensitive == false) {
v = string.toUpperCase();
pattern = pattern.toUpperCase(); //to clarify: pattern should be uppercased also if caseSensitiveness is false
} else {
v = string;
}
return v.indexOf(pattern);
}
EDIT 2:
And url1() is finally like this:
function url1(pages,pattern) {
var siteContent = [];
for(i=0;i<pages.length;i++) {
var seperator = pages[i].charAt(0);
if(pages[i].indexOf(seperator)>=0){
siteContent = pages[i].split(seperator);
}
if( index(siteContent[2],pattern,false)>=0){
return siteContent[1];
}
}
return "";
}
In this case, the first occurrence of pattern in all pages will be returned.

If Else Conditionals within Function in JavaScript

I'm having issues with conditionals. I want to return the index where pattern starts in string (or -1 if not found). The search is to be case sensitive if the 3rd parameter is true otherwise it is case insensitive.
Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1
Any idea how I can accomplish this?
This is my code so far
var s = "abAB12"
var p = "AB"
var cs = true
function index(string, pattern, caseSensitive) {
if (pattern) {
var found = false;
if (caseSensitive = false) {
if (string.indexOf(pattern.) >= 0) {
found = true;
}
return (found);
else {
return ("");
}
} else if (caseSensitive = true) {
if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
found = true;
}
return (found);
} else {
return ("");
}
}
}
alert(index(s, p, cs));
Fiddle at http://jsfiddle.net/AfDFb/1/
You have some mistype in your code. On the 15th line you have
}
return (found);
else {
This is not not valid. Change it to
return (found);
}
else {
There is another one.
if (caseSensitive = false) {
= used for assignment. You need to use == in if statements when comparing.
Also on the 13th line, there's an extra . after pattern. Remove it.
if (string.indexOf(pattern.) >= 0) {
Your fiddle example
You can use string.search() with a regular expression to accomplish this in one liner:
function index(input, key, caseMatters) {
return input.search(new RegExp(key, caseMatters ? '' : 'i'));
}
Now you can:
index("abAB12","AB",true); // returns 2
index("abAB12","AB",false); // returns 0
index("abAB12","BA",true); // returns -1
index("abAB12","BA",false); // returns 1
You need to use double equals sign == in your if, else statements.
if(caseSensitive == false)
And
if(caseSensitive == true)
You are assigning value inside if condition instead of comparing it.
Try
if (caseSensitive == false) {
and
if(caseSensitive == true)
You'd better use search :
'abAB12'.search(/AB/); // 2
'abAB12'.search(/AB/i); // 0
'abAB12'.search(/BA/); // -1
'abAB12'.search(/BA/i); // 1
The i flag means "case insensitive" ( insensible à la casse :D ).

To add arguments or to add an array?

I have this chunk of code [sourced from different user on this site—thanks!] that I need to modify so that I can check multiple fields instead of just one. I'm not sure if I should be adding arguments to the second function or turn the variable checkString to an array.
function getField(fieldType, fieldTitle) {
var docTags = document.getElementsByTagName(fieldType);
for (var i = 0; i < docTags.length; i++) {
if (docTags[i].title == fieldTitle) {
return docTags[i]
}
}
}
function checkField() {
var checkString = getField('input', 'fieldtocheck').value;
if (checkString != "") {
if (/[^A-Za-z\d]/.test(checkString)) {
alert("Please enter only alphanumeric characters for the field fieldtocheck");
return (false);
}
}
}
I think the best option would be to feed "getfield" into the the "checkfield" as arguments but how would I do that?
Any help appreciated.
I would make your function more generic and use a class to identify the fields:
function checkFields(className, regex) {
var inputs = document.getElementsByClassName(className);
for (var i = 0; i < inputs.length; i++) {
if (!regex.match(inputs[i].value)) {
return false;
}
}
return true;
}
function validate() {
if (!checkFields('alphanum', /^[A-Za-z\d]+$/)) {
alert('Please enter only alphanumeric characters');
}
}
And your HTML could look like this:
<input type="text" class="alphanum" />
A much simpler (and better, IMO) approach would be to use the jQuery validation plugin.

Categories