Can't get JavaScript SSN Form Validation to work - javascript

I am new to JS and trying to get it so when someone enters a SSN number in a field, it gives them an alert telling them to NOT put a SSN number in there.
HTML:
<form name="card" action="#">
<input type="text" name="field" class="name social" size="60" placeholder="First and Last Name">
<input type="text" name="field" class="phone social" size="60" placeholder="Phone Number">
<input type="text" name="field" class="email social" size="60" placeholder="Email(name#example.com)">
<select class="select">
<option value="My card has not yet arrived">My card has not yet arrived
<option value="Direct Deposit">Direct Deposit
<option value="Suggest a Card">Suggest a Card
<option value="Issues with CARD.com">Issues with CARD.com
<option value="Other">Other
</select>
<textarea name="field" class="text social " cols="60" rows="5" placeholder="How can we help you?"></textarea>
<input type"submit" name="submit" class="subBtn" value="Submit" onclick="warnCC(document.card.field)">Submit</input>
</form>
JS:
<script>
function warnCC()
{
var ssn = document.getElementsByTagName("input");
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (ssn.value.match(pattern))
{
return true;
alert("Please Do Not Enter SSN Info Into This Form");
}
else
{
return false;
alert("yay!")
}
}
</script>
Any help on where I cam going wrong would be very helpful. I'd also prefer it was done on a "onfocusout" if anyone can give me advice on that.

getElementsByTagName and getElementsByClassName both return a list of elements. That list doesn't have a value property. Each of the items on the list has a value property, but not the list.
You'll want to loop through the list of inputs and handle each of them as appropriate, e.g.:
var list = /*...get the list using either method you have in your code...*/;
var index, input;
for (index = 0; index < list.length; ++index) {
input = list[index];
// input.value will be the value of this particular input
}
Side note: querySelectorAll has better support than getElementsByClassName (IE8 has it, for instance, but not getElementsByClassName), so if you want to get a list using a class, you're best off with:
var list = document.querySelectorAll(".the-class-here");

You should also do the alert() before returning from the function ... if you want the alert() dialog to be displayed.

I tweaked your function. You can see it inaction here: http://jsfiddle.net/tBqP2
function warnCC() {
var formElements = document.getElementsByTagName("input");
for (var k in formElements) {
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (formElements[k].value.match(pattern)) {
alert("Please Do Not Enter SSN Info Into This Form");
return false;
}
}
return true;
}

Related

I am trying to prevent someone being able to fill in a text input if the previous drop down menu hasnt been selected

My task is to make a form with drop down menu for title, text input for first name, last name and email and then intrests as checkboxes.
i have succesfully made the form and have put in place messages when something isnt right on the form however now i need stop somone from being able to type in the first name if they havent selected a title or if title === --
i then need to do the same for the last name but with first name rather than title, i should be able to work round that if i know how to do the first one as the only change is the input type.
if anyone could help thatd be great :)
Verry simple example.
By default, the fields are set to "disabled". The script checks for the previous field in the list and if it has content removes the "disabled" from the next field
var list = document.getElementsByClassName('inpt');
for (let i = 0; i < list.length; i++) {
list[i].addEventListener("change", function () {
if (this.value.length > 0) {
checkInputs(this);
}
});
}
function checkInputs(x) {
for (let i = 0; i < list.length-1; i++) {
if (list[i].id === x.id) {
var z = document.getElementById(list[i + 1].id)
z.removeAttribute('disabled');
z.focus();
}
}
}
<select class="inpt" id="first">
<option value="">Select...</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<input class="inpt" id="name" type="text" disabled>
<input class="inpt" id="surname" type="text" disabled>
<input class="inpt" id="age" type="text" disabled>

Assign a number to every user input

My problem is the following I have a checkbox and two text input where the user has to enter their order and for every order I want to asign a number but I do not know how to do so using javascript and HTML. I tried adding one everytime the order button is clicked but it did not seem to work
<form>
<input type="text" placeholder="condiments" id="condiments">
<input type="text" placeholder="name" id="name">
<label for="bigger">Make theese bigger:</label>
<select id="bigger"></select>
</form>
var order = 0;
document.getElementById("orders").addEventListener("click", numOrder);
function numOrder() {
var setOrder= document.getElementById("orders");
setOrder.value = order;
order++;
}
<input type="text" placeholder="condiments" id="condiments">
<input type="text" placeholder="name" id="name">
<label for="bigger">Make theese bigger:</label>
<select id="bigger"></select>
<button id="orders">Place Order</button>
var order= 0;
document.getElementById("orders").addEventListener("click", numOrder);
function numOrder() {
var setOrder = document.getElementById("orders");
setOrder.value = order;
order++;
}
Note that setOrder.value is stored as a string. Should you need to convert to number, use parseInt(setOrder.value).

How to give the user the ability to add another choice data?

I have a select dropdown menu, The user selects one of the options then the related form inputs are shown.
Here is the html:
<select id="relative" name="relative">
<option>Select relative</option>
<option value="father">father</option>
<option value="mother">mother</option>
<option value="brother">brother</option>
</select>
<div id="relative_sections">
<div id="father">
<input type="text" id="father_name" name="father_name" placeholder="Name" />
<input type="email" id="father_email" name="father_email" placeholder="Email" />
<input type="number" id="father_phone" name="father_phone" placeholder="phone" />
</div>
<div id="mother">
<input type="text" id="mother_name" name="mother_name" placeholder="Name" />
<input type="email" id="mother_email" name="mother_email" placeholder="Email" />
<input type="number" id="mother_phone" name="mother_phone" placeholder="phone" />
</div>
<div id="brother">
<input type="text" id="brother_name" name="brother_name" placeholder="Name" />
<input type="email" id="brother_email" name="brother_email" placeholder="Email" />
<input type="number" id="brother_phone" name="brother_phone" placeholder="phone" />
</div>
</div>
CSS code for hiding all the sections:
#mother,
#father,
#brother{
display:none;
}
Javascript code to show/hide sections on changing selected option:
<script type="text/javascript">
function hideAllChildrenButOne(parentId, toRevealId) {
var children = document.getElementById(parentId).children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
document.getElementById(toRevealId).style.display="block";
}
document.getElementById('relative').addEventListener('change', function(){
if (this.value !== '') {
hideAllChildrenButOne('relative_sections', this.value);
}else{
var children = document.getElementById('relative_sections').children;
for (var i=0; i<children.length; i++) children[i].style.display="none";
}
});
</script>
Here is a live fiddle to see what is going on: http://jsfiddle.net/38db59cx
Then I validate the inputs depending on the selected value:
if($_POST['relative'] == 'father'){
//Validate the inputs
}elseif($_POST['relative'] == 'mother'){
//Validate the inputs
}elseif($_POST['relative'] == 'brother'){
//Validate the inputs
}
What I want do is to give the user the ability to select more than one option like ('father' and 'mother') or even all of them then I validate all, But he must at least fill one option data.
How to do this so the user at least select one option, fills the inputs for this option and still could select another option, So that I can validate what he selects?
Most important thing is that the user should select at least one and fill the related ata and can also select more than one.
You could change your select box to either a multiple select or checkboxes. If using checkboxes you would set the name to name='relative[].
Checkboxes:
<label>father<input type="checkbox" name="relative[]" value="father"></label>
<label>mother<input type="checkbox" name="relative[]" value="mother"></label>
<label>brother<input type="checkbox" name="relative[]" value="brother"></label>
MultiSelect
<select name="relative" multiple>
Then in php you can read the data like this:
// create a container to hold the validated results
$aRelative = array();
// if post data exists proceed to check the resutls
if(isset($_POST['relative'])){
// loop over each post value
foreach($_POST['relative'] as $iPos => $a){
// do some validation on the result
if($a != ""){
$aRelative[] &= $a;
}
}
}
if(!empty($aRelative)){
//do whatever with the data
}
So to my understanding, you want user to select multiple option and want to validate them as well. So here is the piece of code which I am sharing. You need to use attribute 'multiple' in your select tag for multiple options to get selected. Here it is:
Click here and check the code, you want to do something similar
In the javascript, you can do something this and add validation for the options.
$('#RNA').submit(function(){
var options = $('#sampleMut > option:selected');
if(options.length == 0){
alert('no value selected');
return false;
}
});
Note: To select more than one option you need to do => press command/CTRL + click options.
Hope it helps a little!

Javascript form validation and show the input/selected result below the submit button

Need to do:
1) If user forget/miss one or more field then should show errors when click submit button.
2) Show those input/selected the result below the submit button.
What I did:
1) In the first and last name field I used html5 tag "required" to show error.
2) I added javascript code for next 4 field. Actually, it works but it works for first radio field only. But if i delete for that specific radio field code then it will works next field select option code only...Similarly is happen next two field.
Don't understanding why not showing all errors at same time?
3) For showing result, I coded for first name, last name and gender but it is not working. And I don't understanding how to code for selected option value and checked box for showing result.
Any help?
function showInput() {
// No:1 For radio button code
var elem = document.forms["formSurvey"].elements['sex'];
len = elem.length-1;
chkvalue = "";
for(i=0; i<=len; i++) {
if(elem[i].checked)chkvalue = elem[i].value;
}
if(chkvalue=="") {
document.getElementById("errorg1").innerHTML = "NO button Checked";
return false;
} else {
var gendershow = document.getElementById("gendershow1").value;
document.getElementById("gendershow1").innerHTML = gendershow;
return true;
}
// No:2 For select option button code
if(document.getElementById("choose").value=="") {
document.getElementById("errorChoose").innerHTML = "Please select session!";
return false;
} else {
var sessionShow1 = document.getElementById("selectSession").value;
document.getElementById("selectSession").innerHTML = sessionShow1;
return true;
}
// No:3 For Check button code
var allchecked = 0;
if(document.getElementById("int").checked)allchecked = 1;
if(document.getElementById("sch").checked)allchecked = 1;
if(document.getElementById("cur").checked)allchecked = 1;
if(allchecked == 0) {
document.getElementById("errorg2").innerHTML = "Please check the value";
return false;
} else {
var checkIt = document.getElementById("checkButton").value;
document.getElementById("checkButton").innerHTML = checkIt;
return true;
}
// No:4 Show the input/selected result
var first_name = document.getElementById("fname").value;
document.getElementById("display_fname").innerHTML = first_name;
var last_name = document.getElementById("lname").value;
document.getElementById("display_lname").innerHTML = last_name;
var tellGender = document.getElementByName("sex").value;
document.getElementById("gendershow1").innerHTML = tellGender;
}
<!DOCTYPE html>
<html>
<head>
<title>CSE </title>
</head>
<body>
<div class="content">
<!-- Enter information about CSE Center -->
<p>
<form name="formSurvey" onsubmit="return showInput()" action="index.html" method="post">
<p>First name: <input type="text" name="fname" id="fname" required> </p>
<p>Last name: <input type="text" name="lname" id="lname" required></p>
<br>
<h4> Gender:</h4>
<p><input type="radio" name="sex" value="Male" id="gender1"> Male</p>
<p><input type="radio" name="sex" value="Female" id="gender2" > Female</p>
<p><input type="radio" name="sex" value="Prefer" id="gender3" > Prefer not to include</p>
<p><span style="color:red;" id="errorg1"></span></p>
<br>
<h4> Which semester do you plan on attending?</h4>
<select id="choose">
<option value="">Choose a session</option>
<option value="summer">Summer 2015</option>
<option value="fall">Fall 2015</option>
<option value="spring">Spring 2016</option>
</select>
<p><span style="color:red;" id="errorChoose"></span></p>
<br>
<h4>How did you hear about PSU?</h4>
<p><span style="color:red;" id="errorg2"></span></p>
<p><input type="checkbox" name="pt" value="Internet" id="int"> Internet Site</p>
<p><input type="checkbox" name="pt" value="School Fair" id="sch" > While attending school fair.</p>
<p><input type="checkbox" name="pt" value="Current Student" id="cur"> Current Student of PSU</p><br>
<input type="submit" value="Submit">
<br>
</form>
<p><span id="display_fname"></span></p>
<p><span id="display_lname"></span></p>
<p><span id="gendershow1"></span></p>
<p><span id="selectSession"></span></p>
<p><span id="checkButton"></span></p>
</p>
</div>
<script src="script.js"></script>
</body>
</html>
From a quick lookover it seems that the reason why it's not showing all the errors at the same time is because of two reasons:
You use an if/elseif/else statement which will only allow for one to be true.
You are returning every time you find something wrong. This will not allow the other statements to run before you return.
So changing the first thing to multiple if statements and then not returning as soon as you find an error will most likely solve your problem.

Set flag when looping through input fields

I have a series of multiple text fields and a text area. I’m looping through the text fields and the text area and checking if there is a value. If there is not a value I set a flag that says pass=false. Otherwise I set pass=true and would like to fire a custom event if everything evaluates to true. The problem is that because one input field evaluates to true it evaluates them all to true even though two of the fields have no value in them. How would I go about doing this if I wanted it so that all fields have to be filled in but still set pass=false if one or two of them are filled in? Any help is greatly appreciated!
JS Fiddle link: http://jsfiddle.net/YyAjp/12/
HTML:
<form name="headerForm">
<label for="fname">*First Name</label>
<input type="text" class="text" id="fname" name="fname" />
<br/>
<label for="mname">*Middle Name</label>
<input type="text" class="text" id="mname" name="mname" />
<br/>
<label for="fname">*Last Name</label>
<input type="text" class="text" id="lname" name="lname" />
<br/>
<label for="notes">*Notes</label>
<textarea name="notes" /></textarea>
Submit
</form>
JQUERY
$(document).ready(function() {
$("#submit").on('click', function() {
var pass;
$("input,textarea,select").each(function() {
if($(this).val() === ''){
pass = false;
$(this).prev('label').css('color','red');
} else {
pass = true;
$(this).prev('label').css('color','black');
}
});
console.log(pass);
if(pass){ alert('trigger custom event') } else { alert('pass failed'); }
});
});
Change
pass = true;
into
pass = pass && true;
and initialize it to true:
$("#submit").on('click', function() {
var pass = true;
http://jsfiddle.net/mblase75/pgM5X/
(You might also want to use $.trim() on the values first.)

Categories

Resources