Cannot validate user input correctly from server? - javascript

How do I check multiple variable inputs at once to ensure that the regex is working? Everytime I enter anything, the form submits and doesn't alert anything.
I have tried test()method of regex validation too, and still no luck.
I am trying to validate user input with the following regex that makes to where anything that is not a number or blank space is considered a wrong input.
var format=/^(\s*|\d+)$/;
It only accepts numbers and blank spaces in the text box.
The following javascript is what I have:
var pitch = document.getElementById("pitch");
var chisel = document.getElementById("chis");
var saw = document.getElementById("saw");
//var arguments = [chisel, saw, pitch];
var format = /^(\s*|\d+)$/;
function regexTest() {
if (!chisel.match(format) && !saw.match(format) && !pitch.match(format)) {
alert("Repressed Action");
return false;
} else {
alert('Thank you');
}
}
<div class="lab">
<form method="post" action="http://weblab.kennesaw.edu/formtest.php">
Chisels: <input type="text" name="chisels" id="chis" size="5" /> Saw: <input type="text" name="saw" id="saw" size="5" /> Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5" />
<br /> Customer Name: <input type="text" name="customer name" size="25" />
<br /> Shipping Address: <input type="text" name="shipping address" size="25" />
<br /> State:
<input type="radio" id="master" name="card" value="master" /><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american" /><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa" /><label for="visa">Visa</label>
<br />
<input type="reset" value="Reset" />
<div class="lab">
<button onclick="regexTest()">Submit</button>
<button onclick="return false">Cancel</button>
</div>

There are a number of issues with your code, below I've refactored it to be a bit easier to read and so it works.
The validation listener should be on the form's submit handler, not the submit button since forms can be submitted without clicking the button. Also, if you pass a reference to the form to the listener, it's much easier to access the form controls by name.
You should get the values of the form controls when the submit occurs, not before. Your code gets the values immediately, before the user has done anything (and possibly before the form even exists), so put that code inside the listener function.
Lastly, the regular expression needs to match anything that isn't a space or digit, so:
/[^\s\d]/
seems appropriate. However, this will still allow the form to submit if the fields are empty (they don't contain non-digits or non-spaces). You'll need to add a test for that.
function regexTest(form) {
// Get values when the function is called, not before
var pitch = form.pitchfork.value;
var chisel = form.chisels.value;
var saw = form.saw.value;
// Test for anything that's not a space or digit
// var format = /^(\s*|\d+)$/;
var format = /[^\s\d]/;
if (format.test(chisel) || format.test(pitch) || format.test(saw)) {
// There must be at least one non-space or non-digit in a field
alert("Repressed Action");
return false;
} else {
alert('Thank you');
// return false anyway for testing
return false;
}
}
<div class="lab">
<form onsubmit="return regexTest(this)">
Chisels: <input type="text" name="chisels" id="chis" size="5"><br>
Saw: <input type="text" name="saw" id="saw" size="5"><br>
Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5"><br>
Customer Name: <input type="text" name="customer name" size="25"><br>
Shipping Address: <input type="text" name="shipping address" size="25">
<br> State:
<select name="states">
<option>Florida</option>
<option>Georgia</option>
<option>Alabama</option>
</select>
<br>
<input type="radio" id="master" name="card" value="master"><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american"><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa"><label for="visa">Visa</label>
<br>
<input type="reset" value="Reset">
<div class="lab">
<button>Submit</button>
<button onclick="return false">Cancel</button>
</div>
Hopefully this gets you to the next step.

Related

Save Data to Localstorage and use it to populate fields after submit

I have optin popup of two steps, first step is to capture email and name, when user click submit the data is captured, and another popup appears, the new popup has a form with more fields to get more info, plus email and name field.
what I want to do is to automatically populate the email and name field from first popup and hide them with display:none so user can't see them, after submit the data is captured again (all goes to activecampaign).
the two forms works just fine, what is not working is saving the data and calling it when needed
here is the js I'm using
jQuery(function($){
// PART I: Saving user details locally
$('#arlington-field-submit').on('click', function(){
// check if the user's browser has localStorage support
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// store the full name in localStorage
var fullname = document.querySelector("input[name=arlington-name]");
localStorage.user_name = fullname.value;
// save the email in localStorage
var email = document.querySelector("input[name=arlington-email]");
$("input[name=fullname]").val(localStorage.getItem("server"));
localStorage.user_email = email.value;
}
});
// PART II: Pre-filling forms forms with locally saved values
if (typeof(Storage) !== "undefined") {
// check if the user has a name field stored
if (localStorage.user_name) {
name_field = document.querySelector("._form input[name=fullname]");
name_field.value = localStorage.user_name;
}
// check if the user has an email field stored
if (localStorage.user_email) {
email_field = document.querySelector("._form input[name=email]");
email_field.value = localStorage.user_email;
}
}
});
first form html:
<div id="arlington-element-form" class="arlington-element-form arlington-element" data-element="form">
<div id="arlington-form" class="arlington-form arlington-has-name-email arlington-has-buttons">
<div class="arlington-form-wrap"><input id="arlington-field-comments" name="arlington-comments" type="text" data-selectable="true" data-target="#builder-setting-comments_value" class="arlington-field-comments" placeholder="" value="" style="" autocomplete="off"><input id="arlington-field-name" name="arlington-name" type="text" data-selectable="true" data-target="#builder-setting-name_value" class="arlington-field-name" placeholder="Enter your name here..." value="">
<input id="arlington-field-email" name="arlington-email" type="email" data-selectable="true" data-target="#builder-setting-email_value" class="arlington-field-email" placeholder="Enter your email address here..." value="" >
<input id="arlington-field-submit" name="arlington-submit" type="submit" data-selectable="true" data-target="#builder-setting-submit_value" class="arlington-field-submit" value="JOIN NOW" >
</div>
<div class="arlington-yesno-wrap">
<button id="arlington-button-yes" type="button" name="arlington-yes" data-selectable="true" data-target="#builder-setting-yes_value" data-action="form" data-type="yes" class="arlington-button-yes arlington-button-yesno">Submit!</button>
</div></div></div>
second form html:
<form method="POST" action="xxxxxx" id="_form_8_" class="_form _form_8 _inline-form _dark" novalidate> <input type="hidden" name="u" value="8" /> <input type="hidden" name="f" value="8" /> <input type="hidden" name="s" /> <input type="hidden" name="c" value="0" /> <input type="hidden" name="m" value="0" /> <input type="hidden" name="act" value="sub" /> <input type="hidden" name="v" value="2" />
<div class="_form-content">
<div class="_form_element _x72304349 _full_width "> <label class="_form-label"> Full Name </label>
<div class="_field-wrapper"> <input type="text" name="fullname" placeholder="Type your name" /> </div>
</div>
<div class="_form_element _x10201592 _full_width "> <label class="_form-label"> Email* </label>
<div class="_field-wrapper"> <input type="text" name="email" placeholder="Type your email" required/> </div>
</div>
<div class="_form_element _x29901314 _full_width "> <label class="_form-label"> Phone </label>
<div class="_field-wrapper"> <input type="text" name="phone" placeholder="Type your phone number" /> </div>
</div>
<div class="_button-wrapper _full_width"> <button id="_form_8_submit" class="_submit" type="submit"> Submit </button> </div>
<div class="_clear-element"> </div>
</div>
</form>
Since the input which is being clicked is a submit button, chances are that the page is navigating before the JS within the click handler gets a chance to fire.
Try and replace
$('#arlington-field-submit').on('click', function(){
with:
$('#_form_8_').on('submit', function(event){
Then you can prevent the form from actually submitting so your JS can run:
$('#_form_8_').on('submit', function(event){
event.preventDefault();
// Do localStorage stuff
$(this).submit(); // submit the form normally after localStorage is saved
});
The way you look for elements is wrong, because you forgot quotes wrapping attribute values:
var fullname = document.querySelector("input[name=arlington-name]");
should be:
var fullname = document.querySelector('input[name="arlington-name"]');
And so on...
BTW I'm surprised you don't report an error like "An invalid or illegal string was specified".

how do i clone a multiple html input field with jquery

i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)

jQuery - Checking value of various input types

I have no idea what I'm doing wrong here. I have a form with radio buttons and simple text fields. I'm checking to see if there is a value within the form fields or if either of the radio buttons have been checked. If there is no value add a red color to the label. If they have a value I'm adding back the default black. But for some reason no matter if I put a value in the text field it stays red. Also kind of strange but if I check the first checkbox the black text appears. Any help is greatly appreciated.
JS Fiddle: http://jsfiddle.net/5Sacj/
<form name="headerForm">
<label id="gender" for="gender">Gender</label>
<input type="radio" name="customer" value="male" />Male
<input type="radio" name="customer" value="female" />Female
<br/>
<label for="fname">*First Name</label>
<input type="text" class="text" id="fname" name="fname" />
<br/>
<label for="fname">*Last Name</label>
<input type="text" class="text" id="lname" name="lname" />
<input id="submit" type="submit" name="submit" value="submit"
</form>
JQUERY
$(document).ready(function() {
$("#submit").on('click', function() {
$(":text, :radio").each(function() {
if($(this).val() === '' || !$(this).is(':checked')){
$(this).prev('label').css('color','red');
} else {
$(this).prev('label').css('color','black');
}
});
});
});
That is because you are using or operator ||.
It will execute even if one is true. Try using && or have separate if condition for both.

How to validate a form in jsp using javascript before submit

<form name="Details" method="post" action="insertData.jsp" onSubmit="return ValidateForm();">
<label> Name </label > <input type="text" name="name" id="test1" > </input>
<label> ID </label > <input type="text" name="id" id="test2" > </input>
<label> Time </label > <input type="text" name="time" id="test3" > </input>
<label> Latitude </label > <input type="text" name="latitude" id="test4" > </input>
<label> Longitude </label > <input type="text" name="longitude" id="test5" > </input>
<input type= " submit" id="test6" value="submit" > </input>
Validation code in js
function ValidateForm()
{
var uname=document.Detail.name;
if(alphanumeric(uname)){
}
return false;
}
function alphanumeric(uname){
var letter=/*[0-9a-zA-Z]+$/;
if(uname.value.match(letter)){
return true;
}
else{
aler("Enter both alpha and number");
uname.focus();
return false;
}
}
The above validation is to allow a textfield to accept both alphabets and numbers but not only numbers. Its returning false on a wrong input but still the data entered entered is submitted to the database. How to avoid this? what is wrong in my code?
I also want to validate form before submit. After every field is entered it should be validated and displayed if any error just below the field. How do i do it?
You could use a naming pattern for the Ids of hidden <span> tags that represent the form field error messages:
<form onsubmit="return ValidateForm(this);">
<p>
<input type="text" id="name" name="name">
<span style="display: none;" id="name-validation-message"></span>
</p>
</form>
<script>
function ValidateForm(form) {
if (!alphanumeric(form.elements.name)) {
var message = document.getElementById(form.elements.name.id + "-validation-message");
message.innerHTML = "Must be alphanumeric";
message.style.display = "";
}
}
</script>
The elements property on form objects is a key-value store where the keys are the values of the name attribute on the form fields, and the values are either a reference to a single form field DOM node, or a collection.
Consider the following HTML:
<form id="test">
<input type="text" name="foo">
<input type="checkbox" name="bar" value="1">
<input type="checkbox" name="bar" value="2">
<input type="checkbox" name="bar" value="3">
<input type="checkbox" name="bar" value="4">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
</form>
We have three unique form field name attribute values:
foo
bar
things[]
In JavaScript, we'll have the following object model:
var form = document.getElementById("test");
form.elements; // A collection of references to all form fields
form.elements.foo; // Reference to <input type="text" name="foo">
// A DOM node collection referencing all checkboxes whose name is "bar"
form.elements.bar;
form.elements.bar[0]; // First "bar" checkbox
form.elements.bar[1]; // Second "bar" checkbox
// A DOM node collection referencing all text boxes whose name is "things[]"
form.elements["things[]"];
form.elements["things[]"][0]; // First "things[]" textbox
form.elements["things[]"][1]; // Second "things[]" textbox
Many server side languages turn field names with square brackets into arrays. You can access those fields in JavaScript using the Array Notation (e.g. form.elements["bar"] instead of Dot Notation (e.g. form.elements.bar).
Hope the following code helps.
<HTML>
<HEAD>
<TITLE>Verifying User Data</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function checker()
{
var regExp1 = '/^(\d{1,2})\/(\d{1,2})\/(\d{2})$/' ;
var result1 = document.form1.text1.value.match(regExp1);
if (result1 == null || <*any other input doesnt satisfy the required format*>) {
alert("Sorry, that's not a valid date.");
document.form1.text1.focus(); // or document.<formname>.<element_name>.focus();
return;
} else {
document.form1.action="<NextPage.jsp>" ;
document.form1.method="GET"; // or "POST"
document.form1.submit();
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Verifying User Data</H1>
<FORM NAME="form1" >
Please enter a date:
<INPUT TYPE="TEXT" NAME="value1">
<INPUT TYPE="<sometype>" NAME="value2">
<INPUT TYPE="<sometype>" NAME="value3">
..
..
<INPUT TYPE="button" onclick="checker()">
</FORM>
</BODY>
Write another javascript on submit button like
<input type= " submit" id="test6" value="submit" onclick="return save();">
<script>
function save(){
document.form[0].submit;
}
</script>

jQuery Radio Button function not working properly

I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!

Categories