Basic form validation - javascript

I am trying form validation in Javascript, but I am stuck on something.
I have gotten the validation working, but cannot display the contents of each field in the textarea of the form at the bottom.
Any idea how I would do this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
if( document.myForm.room.value == "" ) {
alert( "Please select a room option." );
return false;
}
if( document.myForm.activity.value == "" ) {
alert( "Please select an activity." );
return false;
}
if( document.myForm.hotelname.value == "-1" ) {
alert( "Please select a hotel name." );
return false;
}
if( document.myForm.name.value == "" ) {
alert( "Please provide your name." );
document.myForm.Name.focus() ;
return false;
}
// Use isNaN to check whether there is an illegal number
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 5 ) {
alert( "Please provide a zip code in 5 digit format." );
document.myForm.zip.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form name="myForm" action="" onsubmit="return(validate());">
Type of room: <br />
<input type="radio" name="room" value="basic">Basic<br>
<input type="radio" name="room" value="luxury">Luxury
<br /><br />
Activity: <br />
<input type="checkbox" name="activity" value="swimming">Swimming<br>
<input type="checkbox" name="activity" value="fishing">Fishing
<br /><br />
Hotel name: <br />
<select name="hotelname" multiple="multiple">
<option value="-1" selected>Select...</option>
<option value="1">Hilton</option>
<option value="2">Hampton Inn</option>
<option value="3">Holiday Inn</option>
</select>
<br /><br />
Conferee's name:<input type="text" name="name">
<br /><br />
Conferee's zip code:<input type="text" name="zip">
<br /><br />
<input type="submit" value="Submit" />
<br /><br />
<textarea rows="10" cols="50"></textarea>
</form>
</body>
</html>

// Use isNaN to check whether there is an illegal number
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 5 ) {
alert( "Please provide a zip code in 5 digit format." );
document.myForm.zip.focus() ;
return false;
}
// create the textarea content string
var fields_contents = "";
fields_content += "room : " + document.myForm.room.value + "\n";
fields_content += "activity : " + document.myForm.activity.value + "\n";
fields_content += "hotelname : " + document.myForm.hotelname.value + "\n";
fields_content += "name : " + document.myForm.name.value + "\n";
fields_content += "zip : " + document.myForm.zip.value + "\n";
//set the textarea content
document.getElementById('my_textarea').value = fields_content;
//and then return false for the form not to be submitted
return false;
Notice I use an id to find the textarea : you should add it in your html.
The \n char is line break.
This version implies your form not to be submitted. The thing is that here we get inputs values directly by reading their value property. If the form was submitted, the page would be refreshed, and the inputs values would be empty then.
In this case, the solution would be to get the sent values with PHP, and then use these values directly in Javascript, like that :
var room_value_sent = '<?php echo $_REQUEST['room']; ?>';
fields_content += "room : " + room_value_sent + "\n";
The return false at the end is because of the need not to submit the form. When you do something like onsubmit="return my_function();", if my_function returns false then the form is not submitted (= no page refresh and no request is done).

Sorry for answering instead of commenting - repuration limitations. You can try using Parsley.js library which provides clean code and works out of the box for almost any form you can imagine. Have a look here:
Parlsey.js

Related

Checking if integer JavaScript forms

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.";
}

How to validate empty value using javascript?

Here is html code for text field what to check for empty/null values
function myFormValidation() {
alert("HI");
var name = document.getElementById("name").value;
alert(name);
if (name == null || name == " ") {
document.getElementById("inp1").innerHTML = "Enter your name please";
} else {
document.myForm.submit();
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" name="inp1" />
<input type="button" value="Register" onclick=" myFormValidation()" />
I want to validate using innerHtml, but my js is not getting called.
I guess removing the space between " " may work
your code
if(name==null || name ==" " ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
change to
if(name==null || name =="" ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
You might like to validate the input edit through the help of regular expressions
if ( name == null || /\s*/g.test(name) )
{
document.getElementById("inp1").innerHTML = "Enter your name please";
}
The expression \s* covers both the empty string as well as the input consists of multiple blank spaces, such as " " for example
I'm not really familiar with JavaScript/jQuery but I think this is what you're looking for. I've changed your input for the message to label because your type is hidden which also means that users will not be able to see the message at all.
Also, you didn't include the id attribute for your inp1 so it's impossible to use getElementbyId().
function myFormValidation() {
if (document.getElementById("name").value == "") {
document.getElementById("inp1").innerHTML = "Enter your name please";
}
else {
var name = document.getElementById("name").value;
alert("HI");
alert(name);
document.myForm.submit();
}
}
Name:
<input type="text" name="name" id="name" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<label id="inp1"></label>
Here is example:
function myFormValidation() {
var user = document.getElementById("name").value;
if (user === "") {
document.getElementById("body").innerHTML = "Enter your name please";
} else {
document.getElementById("body").innerHTML = user + " " + "How are you..!";
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<div id="body"></div>

PHP, HTML and Jquery: Dynamic User Info

I'm working on a PHP form for inputting user information. I have these 3 important fields: First Name, Last Name, and E-mail. What I need to do is to set the E-mail automatically when the user enters the first two fields and before saving. For example when the user types 'First' in the First Name and 'Last' in the Last Name fields, the E-mail field should automatically show First.Last#example.com.
The code is already written and this is the part I'm working on:
echo '<TABLE ><TR><TD >'.TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','<FONT color=red>'._('First').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]',''._('Middle').'','class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['LAST_NAME'],'students[LAST_NAME]','<FONT color=red>'._('Last').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]',''._('Suffix').'',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"').'</TD></TR></TABLE>';
else
echo '<DIV id=student_name><div style="font-size:14px; font-weight:bold;" onclick=\'addHTML("<TABLE><TR><TD>'.str_replace('"','\"',TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]','','size=3 maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['LAST_NAME'],'students[LAST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]','',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"',false)).'</TD></TR></TABLE>","student_name",true);\'>'.$student['FIRST_NAME'].' '.$student['MIDDLE_NAME'].' '.$student['LAST_NAME'].' '.$student['NAME_SUFFIX'].'</div></DIV>';
echo'</td></tr>';
echo '<tr><td>'._('Email').'</td><td>:</td><td>'.TextInput($student['EMAIL'],'students[EMAIL]','','size=100 class=cell_medium maxlength=100').'</td></tr>';
I don't know how I'm supposed to edit it or where to add the jquery code.
Note: I already have the following options as I've asked this question before:
Option1 :
$('body').on('blur', '.firstname, .lastname', function(){
var fname = $.trim($('.firstname').val()),
lname = $.trim($('.lastname').val()),
email = $('#email'),
// Set your domain name here
prefix = '#example.com';
if( fname != "" && lname != "" )
email.val( fname + '.' + lname + prefix );
else if( fname == "" && lname == "" )
email.val("");
else
email.val( (fname != "" ? fname : lname) + prefix );
});
Option2:
$('#firstName', '#lastName').keyup(function() {
var domain = 'example.com';
var email = $('#firtName').val() + '.' + $('#lastName').val() + '#' + domain;
$('#email').val(email);
});
My Problem is that I don't know how to apply any of this in my code.
Yes you can do this
if you have fields like this
<input type="text" name="fn" value="" id="firstname" maxlength="30" />
<input type="text" name="ln" value="" id="lastname" maxlength="30" />
<input type="text" name="em" value="" id="email" maxlength="30" />
put the following script at the bottom of your html content
dont forget to add the jquery library
<script type="text/javascript">
$("#lastname").blur(function() { //blur event is called when the textbox lost focus
var vall = $("#firstname").val()+$("#lastname").val()+"#example.com";
$("#email").val(vall);
}) ;
</script>
comment for further changes...
var namehandler = function(){
var firstname = $('[name="students[FIRST_NAME]"]');
var lastname = $('[name="students[LAST_NAME]"]');
var email = $('[name="students[EMAIL]"]');
if (firstname.val() == '' || lastname.val() == ''){
email.val('');
return;
}
email.val(firstname.val() + '.' + lastname.val() + '#email.com');
};
$(document).ready(function(){
$('[name="students[LAST_NAME]"]').keyup(namehandler);
$('[name="students[FIRST_NAME]"]').keyup(namehandler);
});
Here's a link to the JSFiddle: http://jsfiddle.net/xw44gwvt/1/
This makes the email change instantly when the first or last name changes using the keyup event.
EDIT:
I changed the selector to get element by name. Maybe this will help, let me know if it works. If not, I'll see what i can do otherwise.

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