facing comparision issue in javascript - javascript

this is what is my java script function :
function issueOrReturn() {
var functiontype = document.getElementById("functiontype").value;
alert("functiontype : "+functiontype);
if (functiontype=="issueTempcard") {
alert("1111111111111111111111111");
var empid = document.getElementById("empid").value;
var tempcardnumber = document.getElementById("tempcardnumber").value;
var dateofissue = document.getElementById("dateofissue").value;
if(empid.length==0) {
alert("Please enter Employee ID ");
return false;
}
if(tempcardnumber.length==0) {
alert("Please enter Card Number ");
return false;
}
if(dateofissue.length==0) {
alert("Please enter Date of issue ");
return false;
}
if(empid.length > 0 && tempcardnumber.length > 0 && dateofissue.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and and Card Number and Date of issue ");
return false;
}
}
if (functiontype == "returnTempCard") {
alert("222222222222222222222222222222");
var empid = document.getElementById("empid").value;
var dateofreturn = document.getElementById("dateofreturn").value;
if (empid.length == 0) {
alert("Please enter Employee ID ");
return false;
}
if (dateofreturn.length == 0) {
alert("Please enter Date of return ");
return false;
}
if (empid.length > 0 && dateofreturn.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and Date of return ");
return false;
}
}
}
here the functiontype is : issueTempcard the alert is printed but it is not getting in the if loop of issueTempcard hence the form is not submitted,
also please advise me whether the following way is correct to submit the form :
if (empid.length > 0 && tempcardnumber.length > 0 && dateofissue.length > 0) {
document.forms["frmTempcard"].submit();
} else {
alert("Please enter Employee ID and and Card Number and Date of issue ");
}
kindly provide me some help so that i can do it.
Regards,

Both your function definitions miss their closing } character.
Because of this, they are not executed (because the javascript interpreter fails to read your entire function)
This JsFiddle shows your code up and running without a hitch.
All i did is add the }
To help you debug your JS code, try using Firebug, which can show you where you went wrong ;)
Your way of submitting forms looks fine to me, but is also missing the trailing }

Related

How can I use conditional logic with JavaScript form validation?

I have the following JavaScript function which is triggered by an onclickevent and is working fine.
<script>
function validateForm() {
let xgame_name = document.forms['myForm']['game_name'].value;
if (xgame_name == '') {
alert('Game Name must be filled out');
return false;
}
let xdev_name = document.forms['myForm']['developer_name'].value;
if (xdev_name == '') {
alert('Developer Name must be filled out');
return false;
}
let xdev_email = document.forms['myForm']['email'].value;
if (xdev_email == '') {
alert('Developer Email must be filled out');
return false;
}
let xdemo_rom = document.forms['myForm']['demo_rom'].value;
if (xdemo_rom == '') {
alert('Demo Rom must be uploaded');
return false;
}
let xpromo_image = document.forms['myForm']['promo_image'].value;
if (xpromo_image == '') {
alert('Promo must be uploaded');
return false;
}
}
</script>
I am trying to add this so if one of the radio buttons with a value of 1 is selected on the form it will check an additional field to see if there is a value and show an alert.
let xcartridge = document.forms['myForm']['cartridge'].value;
if (xcartridge == '1') {
let xcover_art = document.forms['myForm']['cover_art'].value;
if (xcover_art == '') {
alert('If Cartridge is selected you must proved Cover Art');
return false;
}
}
This follows the same syntax of the above code example that is working but this does not send an alert but rather the form validation does not work at all. How can I get the alert to show when one fields condition is met, where it is 1 and that prompts an alert on an additional field?

Try to validate IP Address with javascript

I'm a beginner to javascript. Now, I'm trying to make a form to post back to server. There are some "input" that contains ip address which should be validate before submitting. Now I have done a javascript function which work well. But now I'm trying to add this function into jquery selection. Just confuse how to do it.
This is my validate javascript code.
function ValidateIPaddress(Ipfield)
{
IpAddr=Ipfield.value;
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(!IpAddr.match(ipformat))
return true;
else
return false;
}
and this is now how I implement for this validation.
<input type= "text" name= "LocalIP" style= "margin-right:10px " value="192.168.1.193" class="ip" onfocusout="ValidateIPaddress(document.getElementById('LocalIp'))" id="LocalIp" > Remote VIP Address :
<input type= "text" name= "RemoteVIPAddr" style= "margin-right:10px" value="234.5.6.7" class="ip" onfocusout="ValidateIPaddress(document.getElementById('RemoteIp'))" id="RemoteIp" >
Remote VIP Port :
<input type= "text" name= "RemoteVIPPort" style= "margin-right:10px" value="5004" class="ip" onfocusout="ValidatePort(document.getElementById('RemoteVIPPort'))" id="RemoteVIPPort">
Now I want to use jquery selection to always check if there are some invalid input. Which is something like this but with my own design function.
$("input.ip:visible").filter(function() { return this.ValidateIPaddress === true }).addClass("invalid");
Anyone has idea bout it?
You're not calling ValidateIPAddress in your filter function, you're just testing whether the DOM element has a non-empty property named ValidateIPAddress. It should be:
$("input.ip:visible").filter(function() {
return ValidateIPAddress(this);
}).addClass("invalid");
Try this:
isIP(ip) {
if (typeof(ip) !== 'string')
return false;
if (!ip.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
return false;
}
return ip.split('.').filter(octect => octect >= 0 && octect <= 255).length === 4;
}
Original: https://stackoverflow.com/a/50612630/3261332
And if one needs to accept also CIDR format IP/{0-32} please update the 2 lines as below:
if (!ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/([0-9]|[12][0-9]|3[0-2]))?$/)) {
return ip.split('/')[0].split('.').filter(octet => octet >= 0 && octet <= 255).length === 4;
See if this help. This is valid fo IP4 only.
0.0.0.0 - Invalid
Any ip with CIDR is invalid
function validateIP(ip) {
is_valid = false;
ip = ip.replace(/\s+/, "");
if(ip.indexOf('/')!=-1){
alert("IP not valid");
return false
}
try {
var ipb = ip.split('.');
if (ipb.length == 4) {
for (i = 0; i < ipb.length; i++) {
b = parseInt(ipb[i]);
if (b >= 0 && b <= 255) {
is_valid = true;
} else {
is_valid = false;
break;
}
}
}
} catch (exception) {
alert("IP is not valid")
return false;
}
if (!is_valid) {
alert("IP is not valid")
return false;
}
return true;
}

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

javascript validation numerical

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}
You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>
Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

Validating Checkboxes - Not detecting it's checked

I've been struggling over this all day. All the other validation works fine except for the check boxes. It seems to validate it but doesn't detect when things are checked. Meaning, I'll check a box and it'll still say to enter in a contact time, no matter what box I check. Please help!!
Its just the one for selecting the best time to contact you that's acting up.
Here's my check boxes:
<input id="best_contact_time" name="best_contact_time" value="Morning 7-12" class="inputCheckbox" type="checkbox">Morning (7-12)<br>
<input id="best_contact_time" name="best_contact_time" value="Afternoon 12-5" class="inputCheckbox" type="checkbox">Afternoon (12-5)<br>
<input id="best_contact_time" name="best_contact_time" value="Evening 5-9" class="inputCheckbox" type="checkbox">Evening (5-9)<br>
And my validation code:
function submitme() {
// Validate required fields
if (get_element('lastname').value == '') {
alert('Please enter your last name');
return false;
}
if (get_element('first_name').value == '') {
alert('Please enter your first name');
return false;
}
if (get_element('phone').value == '') {
alert('Please enter a phone number');
return false;
}
if (get_element('email').value == '') {
alert('Please enter an email address');
return false;
}
var ischecked = 0;
for (var i = 0; i < document.rental.best_contact_time.length; i++) {
var e = document.rental.best_contact_time;
if (e.checked == true)
{ ischecked = 1; }
}
if (ischecked == 0) {
alert('Please enter the best time to contact you');
return false;
}
if (get_element('approximate_start_date').value == '') {
alert('Please enter an approximate start date');
return false;
}
document.forms[0].submit();
return true;
}
Since you have multiple elements with the same name, document.rental.best_contact_time will be a NodeList not an HTMLElementNode.
You would need to loop through the list (treat it like an array) and check each one in turn.

Categories

Resources