Prevent submission of form for non numeric fields - javascript

I am trying to set up a form validation - this works - but only for odd numbers, if you enter an even number, e.g. part number TEST and quantity 2 then the alert will come up, if you enter qty 3 then the form will submit. Any ideas ?
Javascript
<script type="text/javascript">
function allnumeric(inputtxt)
{
var numbers = /^[0-9]+$/;
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
{
return true;
}
else
{
alert('Please input numeric characters only or fill in the product field')
{
return false;
}
}
}
</script>
Form
<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">
<input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>
<input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>
<input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>
</form>
Thanks all - it was the typo, if(form2.qty.value.match(numbers) & (form2.product.value != "")) changed to if(form2.qty.value.match(numbers) && (form2.product.value != "")) and it now works.

Assuming you're targeting html5:
<input name="qty" type="number" id="qty" style="height:55px;font-size:30pt;"/>
Or if you really want to have type="text":
<input name="qty" type="text" id="qty" pattern="\d+" style="height:55px;font-size:30pt;"/>
Also, you've got a typo:
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
should be
if(form2.qty.value.match(numbers) && (form2.product.value != ""))

Inside of your if condition you have to add one more if condition to check the odd and even number. You have to do this:
if(form2.qty.value.match(numbers) & (form2.product.value != ""))
{
var num = form2.qty.value;
if(num%2 == 0) {
alert('Even number');
} else {
return true;
}
}

function allnumeric(inputtxt)
{
var numbers = /^[0-9]+$/;
var qty = form2.qty.value;
if(qty.match(numbers) && (form2.product.value != ""))
{
if(qty & 1) // even number
return true;
else
alert('Even number');
return false;
}
else
{
alert('Please input numeric characters only or fill in the product field')
return false;
}
}
<form id="form2" name="form2" method="post" action="booking-printlabel2.asp?insert=yes" onsubmit="return allnumeric()">
<input name="product" type="text" id="product" style="height:55px;font-size:30pt;" size="10"/>
<input name="qty" type="text" id="qty" style="height:55px;font-size:30pt;" size="3"/>
<input type="submit" name="Print Labels2" id="Print Labels2" value="Print Labels" style="height:55px;font-size:30pt;"/>
</form>

Related

How to check calculation answer of 2 input fields before submitting form

I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}

javascript form validation issue

for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">
You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>
try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'
I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">
function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}

show/hide div if input is 0 or default

I´m working in a payment gateway where the user Name the Price for my digital books. An input box (to text the price) and a "Pay now" button are displayed. BUT:
If the price is less than 0.50 the payment button disapear and the download button appear
If the user introduce a "," instead a "." a box is displayed (please, enter a valid number)
Here is the form with the input box:
<form id="hikashop_paypal_form" name="hikashop_paypal_form" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="X" />
<input type="hidden" name="item_name_1" value="X" />
<input id="amount_1" name="amount_1" class="amount_1"/></form>
Pay Now button (it should be hiden if 1 is true)
<div id="PayNow" class="PayNow">
<input id="PayNow_button" type="submit" class="btn btn-primary" value="Pay now" name="" />
</div>
Download Now Button (it should be shown if 1 is true)
<div id="downloadNow" class="downloadNow">
Download now
</div>
Info box (It should be shown if 2 is true)
<div id="info" class="info">
Enter a valid number
</div>
And the question is: How can I do it?
I supose the solution passes by using javascript, but I don´t know how exactly... Thanks for you time...
I don´t know how, but it works for me:
Try it here: IBIZA! Book Download
<form id="pplaunch" action="https://www.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input id="issueid" name="issueid" type="hidden" value="ARCHIVE NAME">
<input type="hidden" id="currency" name="currency" value="EUR">
<input type="hidden" name="business" value="YOUR PAYPAL ID" />
<input type="hidden" value="0" name="test_ipn"></input>
<input type="hidden" name="item_name" value="PRODUC NAME">
<input type="hidden" value="1" name="no_shipping"></input>
<input type="hidden" value="0" name="no_note"></input>
<input type="hidden" value="utf-8" name="charset"></input>
<input type="hidden" value="Super" name="first_name"></input>
<input type="hidden" value="http://www.YOURWEBSITE.com/return" name="return"></input>
<input type="hidden" value="http://www.OURWEBSITE.com/cancel" name="cancel_return"></input>
<div class="nameprice" style="float:left;margin-right:15px;>
<span style="font-size:small;">Name your price: </span><input id="amount" name="amount" size="6" maxlength="5" type="text"> <span style="font-size:small;color:#ccc;">From 0.00€</span>
</div>
<div id="pricerror"></div>
<div class="buttonspace">
<button id="buybutton" class="buybutton" type="button">Checkout</button>
<div id="descargaGratisMensaje"></div>
<div style="display: block;" class="pay">
</div>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function newPopup(url, width, height){
popupWindow = window.open(url,'_blank','height='+height+',width='+width+',left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes');
return false;
}
function displaybutton(displayclass){
if(displayclass == 'pay'){
$('.pay').css('display','block');
$('#pplaunch').attr('action', 'https://www.paypal.com/cgi-binwebscr');
$('#buybutton').html('Pagar');
}else{
$('.pay').css('display','none');
$('#pplaunch').attr('action', 'http://www.example.com/archive/'+$('#issueid').val());
$('#buybutton').html('Descargar');
$('#descargaGratisMensaje').html('Un Me Gusta podría ser un buen intercambio');
}
}
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n) && (n.search(/0x/i)<0);
}
function price(n){
// return null if n is not a price, or n rounded to 2 dec. places
if(!isNumber(n)){
// maybe the user entered a comma as a decimal separator
n = n.replace(/,/g,'.');
if(!isNumber(n)){
return null;
}
}
// now we know it is a number, round it up to 2 dec. places
return Math.round(parseFloat(n)*100)/100;
}
function pricecheck(){
var data = $.trim($('#amount').val());
var myprice = price(data);
if(myprice == null){
if(data == ''){
$('#pricerror').html('');
}else{
$('#pricerror').html('Please enter a price.');
}
displaybutton('pay');
return false;
}
if(myprice == 0){
$('#pricerror').html('');
displaybutton('nopay');
}else if(myprice < 0.5){
$('#pricerror').html('The minimum price is '+currencysymbol+'0.50.
Please enter either zero, or at least '+currencysymbol+'0.50.');
displaybutton('pay');
}else{
$('#pricerror').html('');
displaybutton('pay');
}
jQuery('.content').hide();
}
var currencysymbol = '$';
$.getScript('//www.geoplugin.ne/javascript.gp?ref=panelsyndicate.com', function() {
if(geoplugin_continentCode() != 'EU'){return;}
$('#currency').val('EUR');
currencysymbol = '€';
$('.currencysymbol').html(currencysymbol);
});
$(document).ready(function(){
var dialog = $('#modal').dialog({
title: 'IBIZA!'
, autoOpen: false
, closeText: ''
, modal: true
, resizable: false
, width: 500
});
$('#buybutton').click(function() {
$('#pplaunch').submit();
});
$('#pplaunch').submit(function() {
var myprice = price($.trim($('#amount').val()));
if((myprice != 0) && ((myprice == null) || (myprice < 0.5))){
$('#pricerror').html('Please enter your price.');
$('#amount').focus();
return false;
}
});
$('.modaltrigger').click(function() {
var issueid = $(this).attr('href').substr(1);
$('#issueid').val(issueid); // Comic ID
$('#include_a_message_to').html(issues[issueid].include_a_message_to); // Destinee of the message
dialog.dialog('option', 'title', issues[issueid].title); // Title of the comic
$('#issuelangs').html(issues[issueid].langs); // Languages in which the comic is available
dialog.dialog('option', 'position', { my: "center", at: "center", of: window });
dialog.dialog('open');
// prevent the default action, e.g., following a link
pricecheck();
return false;
});
$('#amount').bind('input propertychange', function() {
pricecheck();
});
$('.custommsg').hide();
$('.msgtrigger').click(function() {
var cmsg = $('.custommsg');
if(cmsg.is(':visible')){
cmsg.hide();
$('.sendmsg').show();
}else{
$('.sendmsg').hide();
cmsg.show();
$('.msgtxt').focus();
}
return false;
});
$('.msgtxt').keyup(function(){
if($(this).val().length > maxlength){
$(this).val($(this).val().substr(0, maxlength));
}
var remaining = maxlength - $(this).val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
var maxlength = 200;
var remaining = maxlength - $('.msgtxt').val().length;
$('#msgtxtnumcharsleft').text(remaining);
});
</script>

Better way to validate the form field combination with jQuery

I have a sample form with the following code (stripped for JSFiddle)
<input type="text" id="i1" />
<input type="text" id="i2" />
<input type="text" id="i3" />
<input type="text" id="e1"/>
<input type="text" id="e2" />
<input type="text" id="e3" />
<input type="button" id="submit" value="Submit">
The jQuery code follows (stripped for JSFiddle)
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
var a = $("#i1").val();
var b = $("#i2").val();
var c = $("#i3").val();
if (a == "" && b !== "" && c!=="") {
$("#e1").show();
} else if (a !== "" && b == "" && c=="") {
$("#e2").show();
$("#e3").show();
} else if (a !== "" && b !== "" && c=="") {
$("#e3").show();
}else if (a == "" && b == "" && c=="") {
$("#e1").show();
$("#e2").show();
$("#e3").show();
}
});
I am trying to validate the fields with possible combinations. It will show or hide the last three text fields (with id e*)accordingly if the fields are blank or not. For example, if the 1st field is empty and others are not, then e1 should be shown and others are hidden. Same of others like a typical form field were all fields are mandatory. If I write the above code, it is too long and complex. Is there any simple solution for this kind of scenario ?
Thanks
This will do what you want...
$(document).ready(function(){
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
$("input[id*=i]").each(function(i){
if($(this).val()=="") $("#e"+(i+1)).show();
else $("#e"+(i+1)).hide();
});
});
});
$(function(){
$("#e1").hide();
$("#e2").hide();
$("#e3").hide();
$("#submit").click(function(){
var a = $("#i1").val();
var b = $("#i2").val();
var c = $("#i3").val();
if (a == "") {
$("#e1").show();
}if (b == "") {
$("#e2").show();
}if (c == "") {
$("#e3").show();
}
});
})
<input type="text" id="i1" />
<input type="text" id="i2" />
<input type="text" id="i3" />
<input type="text" id="e1"/>
<input type="text" id="e2" />
<input type="text" id="e3" />
<input type="button" id="submit" value="Submit">
Demo

form not validating - javascript

bit of a noob with form validation. I'm trying to get this form to validate on the required fields, and something's amiss. Here's what I'm working with:
html:
<form action="../visit/thankyou.html" method="post" id="vsurvey">
<input type="hidden" name="id" value="503" />
<fieldset>
<legend>Group and Coordinator Information</legend>
<label><span>Group Leader Name<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8149" />
</label>
<label><span>Email<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8155" />
</label>
<label><span>Phone<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8156" />
</label>
<label><span>School/Organization<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8159" />
</label>
<label><span>Program</span>
<input type="text" name="question_8180" />
</label>
<label><span>Grade(s)</span>
<input type="text" name="question_8181" />
</label>
<label><span>Number of Participants<span style="color:#cc2d30">*</span></span>
<input type="text" name="question_8182" />
</label>
</fieldset>
<fieldset>
<label><span>Preferred Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8185" name="question_8185" />
</label>
<label><span>Second Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8186" name="question_8186" />
</label>
<label><span>Third Preference Date<span style="color:#cc2d30">*</span></span>
<input class="date" type="text" id="question_8187" name="question_8187" />
</label>
<label>Special Accommodations
<input type="text" name="question_8174" />
</label>
</fieldset>
<label>What is the purpose or desired outcome of this visit?
<textarea name="question_13026"></textarea>
</label>
<label>How did you learn about our Group Visit Program?
<textarea name="question_8176"></textarea>
</label>
<label>Comments
<textarea name="question_8184"></textarea>
</label>
<input type="submit" id="sbutton" value="Submit Request" />
</form>
js:
function validateForm() {
var x = document.forms["vsurvey"]["question_8149"].value;
if (x == null || x == "") {
alert("Please fill in the Group Leader's name.");
return false;
}
var x = document.forms["vsurvey"]["question_8155"].value;
if (x == null || x == "") {
alert("Please fill in the email field.");
return false;
}
var x = document.forms["vsurvey"]["question_8156"].value;
if (x == null || x == "") {
alert("Please fill in the phone field.");
return false;
}
var x = document.forms["vsurvey"]["question_8159"].value;
if (x == null || x == "") {
alert("Please fill in the School/Organization field.");
return false;
}
var x = document.forms["vsurvey"]["question_8182"].value;
if (x == null || x == "") {
alert("Please indicate the number or participants.");
return false;
}
var x = document.forms["vsurvey"]["question_8185"].value;
if (x == null || x == "") {
alert("Please enter your preferred date.");
return false;
}
var x = document.forms["vsurvey"]["question_8186"].value;
if (x == null || x == "") {
alert("Please enter your second date preference.");
return false;
}
var x = document.forms["vsurvey"]["question_8187"].value;
if (x == null || x == "") {
alert("Please enter your third date preference.");
return false;
}
}
http://jsfiddle.net/blackessej/9a6BJ/1/
Currently the form submits the info anyway, but without sending the user to the thankyou page, if all required fields aren't filed in. If all required fields are filed, the thankyou page gets called.
You're not calling validatorForm. Your input button needs to be the following
<input type="submit" id="sbutton" value="Submit Request" onclick="return validateForm()" />
Or use the onsubmit event of your form
<form action="../visit/thankyou.html" method="post" id="vsurvey" onsubmit="return validateForm()">
You need to create an onSubmit event to call validateForm:
document.getElementById('vsurvey').onsubmit = validateForm;

Categories