This is a trivial question, but for some reason I am having trouble with it.
I have HTML for uploading a file such as the following.
<input type="file" name="settings">
And all I need to do is check when the form is submitted that a value has been selected.
I dont need help with the code for the form submission, I just need help since I am guessing
you are unable to validate this as you would other form input fields such as text boxes.
I have tried doing things like...
var file = document.getElementById('settings').value;
if(file.length > 0 == false){
//give error messsage here
I know that there should be an easy fix for this but I cant quite figure it out.
Thanks
I don't see why this would not work - as long as you give the input an id:
<input type="file" name="settings" id="settings">
<input type="file" name="field_name" onchange="validate_file_format('field_name','allowed file format as comma separeated')"/>
Ex:
<input type="file" name="sitemap_doc" onchange="validate_file_format('sitemap_doc','doc,pdf')"/>
JS Code:
======
function validate_file_format(field_name, allowed_ext){
obj1=document.req_form;
var temp_field= 'obj1.'+field_name+'.value';
field_value=eval(temp_field);
if(field_value!=""){
var file_ext= (field_value.substring((field_value.lastIndexOf('.')+1)).toLowerCase());
ext=allowed_ext.split(',');
var allow=0;
for ( var i=0; i < ext.length; i++) {
if(ext[i]==file_ext){
allow=1;
}
}
if(!allow){
alert('Invalid File format. Please upload file in '+allowed_ext+' format');
return false;
}
}
return false;
}
What about just doing:
<input type="file" name="settings" id="settings">
You need to give the code an id attribute with the value "settings". You have a strange if construction.
if(file.length <= 0) { //error message
}
Related
I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function
The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.
I have an issue in validating a file in magento form validator,
i have custom validation code for file size like this.
Validation.add('validate-filesize', 'Upload file should be less than 2MB',function(v,elem) {
var file = elem.files;
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}
});
and in my form there are two file filds.
above validation code is working fine for this field.
<input type="file" id="file1" name="file1" value="" class="input-text required-entry validate-filesize">
but it is failing to validate below field
<input type="file" id="file2" name="file2" value="" class="input-text validate-filesize">
The error doesn't lie in the library, but in your validator callback function.
You are checking the size of the file using the following code
var fileSize = file[0].size
But when the user doesn't upload any files, the variable file[0] is undefined. Thus when you do file[0].size, it throws an error saying Cannot read property 'size' of undefined. And that's why further processing of your code stops and you don't get the desired message.
A good way of doing it would be to check if the user has uploaded any files before checking it's size, like so.
var file = elem.files;
if(file.length == 0) return true; // all is good if user didn't upload any file
//go ahead with the rest of the code otherwise
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}
I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.
I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.
This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:
<form id="colleagues" action="email-sent.php" method="POST">
<input type="hidden" name="user" value="user" />
<textarea id="emails" name="emails" value="emails" placeholder="Example: john#mail.com, thiffany#mail.com, scott#mail.com..."></textarea>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
Here is what I tried in Jquery with no success:
//handle error
$(function() {
$("#error_message").hide();
var error_emails = false;
$("#emails").focusout(function() {
check_email();
});
function check_email() {
if(your_string.indexOf('#') != -1) {
$("#error_message").hide();
} else {
$("#error_message").html("Invalid email form.Example:john#mail.com, thiffany#mail.com, scott#mail.com...");
$("#error_message").show();
error_emails = true;
}
}
$("#colleagues").submit(function() {
error_message = false;
check_email();
if(error_message == false) {
return true;
} else {
return false;
}
});
I hope the question was clear enough, if you need more info please let me know.
Many thanks in advance for all your help and advises.
var array = str.split(/,\s*/);
array.every(function(){
if(!validateEmail(curr)){
// email is not valid!
return false;
}
})
// Code from the famous Email validation
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
Few errors as I noted down:
The code snippet posted here has missing braces }); at the end.
Also, what is your_string variable in the function check_email.
Also, error_message is assigned false always so the submit method will return true always.
Fixing this issues should help you.
I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():
<form id="colleagues" action="" method="POST">
<input type="hidden" name="user" value="user" />
<input name="emails[]" id="starter" placeholder="Email address" />
<div id="addEmail">+</div>
</br><span class="error_message"></span>
<!-- Submit Button -->
<div id="collegues_submit">
<button type="submit">Submit</button>
</div>
</form>
<script>
$(document).ready(function() {
$("#addEmail").click(function() {
$("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
});
});
</script>
Hi please use below js code,
$('#emails').focusout(function(e) {
var email_list = $('#emails').val();
var email_list_array = new Array();
email_list_array = email_list.split(",");
var invalid_email_list=' ';
$.each(email_list_array, function( index, value ) {
if(!validEmail(value))
{
invalid_email_list=invalid_email_list+' '+value+',';
}
});
console.log(invalid_email_list+' is not correct format.');
alert(invalid_email_list+' is not correct format.');
})
function validEmail(v) {
var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return (v.match(r) == null) ? false : true;
}
If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.
thank you
Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...
I have a form that allows for multiple file uploads.
<input name="uploadedfile[]" type="file" multiple="true"/>
Now, I want to validate it using javascript to check if a file was selected. I tried the following but failed
if(form.uploadedfile.length < 1)
{
alert("You Forgot to select an image");
return false;
}
and I know its an array but i also tried
if(form.uploadedfile.value == '')
{
alert("You Forgot to select an image");
return false;
}
can someone help me out on this one.
Thanks
One approach is:
$('input[type="file"][multiple]').change(
function(e){
var numFiles = e.currentTarget.files.length;
if (numFiles == 0){
// no files
}
else {
// files chosen
console.log(numFiles);
}
return false;
});
JS Fiddle.
In this example they use a files property of the input, and check the length of that, something like this.
<input name="uploadedfile[]" id="uploadfile" type="file" multiple="true"/>
And the JS:
if(document.getElementById("uploadfile").files.length < 1)
{
alert("You Forgot to select an image");
return false;
}
Haven't been able to find any info about the files-property yet.
This is my first message here so I hope that newbies also get help :)
My problem is following:
let's start with code first....
javascript:
$(document).ready(function(){
if ($("input#datum2").val() == "")
{
$().click(function(){
$("input#datum2").val($("input#datum1").val());
});
}
});
html:
<form >
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)...
When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition
if ($("input#datum2").val() == "")
works only once.
I'm new to javascript and jquery so I would appreciate for any help.
Thanks in advance!
Cheers,
Ile
Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.
$(function() {
var $datum2 = $('#datum2');
$('#datum1').blur(function() {
if(!$datum2.val())
$datum2.val($(this).val());
});
});
Couple of things:
1) $(function() { ... is a nice shortcut to $(document).ready
2) In JavaScript, an empty string evals to false, so its a nice shortcut.
I see the way round are the order of the click event and "if ($("#datum2",..."
HTML:
<form id="myform">
<input id="datum1" type="text" />
<input id="datum2" type="text" />
</form>
Javascript:
$(document).ready(function(){
$().click(function(){
if ($("#datum2", $("#myform")).val() == "") {
$("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
}
});
});
$(document).ready(function(){
var $datum2 = $('#datum2');
$('#datum2').hover(function() {
if(!$datum2.val())
$datum2.val($('#datum1').val());
});
});