Validate at least 1 file input is completed with jQuery - javascript

How can I ensure that at least one field has a selected file using jQuery? Here is my form:
<form action="b.php">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="submit" value="Value">
</form>

To achieve this you can use map() to build an array of all the valid file input elements. You can then check if this array has any elements in it. If it does, then at least one input was valid, if it was empty then nothing has been chosen. Try this:
var validFields = $('input[type="file"]').map(function() {
if ($(this).val() != "") {
return $(this);
}
}).get();
if (validFields.length) {
console.log("Form is valid");
} else {
console.log("Form is not valid");
}
Example fiddle

You could use jQuery's .val() method to check if a value has been set but I don't know if that works for file input types.
However, you should use a server-side language to validate your files because if you're using javascript, the person browsing the page can just disable the validating. Just loop through the file[] array and check if it's empty or not.
This is much safer and easier as well actually.

While you of course need server-side validation, there are some nice tricks to check if somebody has added a file to your input elements.
Now, your access to the file input element is heavily restricted due to security reasons, so you can't for example change it. You can, however, check the following:
if($('input[type="file"]').val() != "") {
alert("a file is selected")
}

Related

Parsley validation input=file type required error message

I have a form with multiple file upload and the file field is required field with at-least one file is required to upload..
<input type="file" class="upload" name="file[]" multiple required/>
And class upload having on change event function to display list of uploaded files for that field and file type checking purpose.
My problem is on ajax form submit always parsley.validate return false..If i choose files also it returns false.
var check = $('#form').parsley().validate();
alert(check);
Any idea?
Should work. As always, post a live example
you can use this to check number of files in input
if( document.getElementById("uploadFile").files.length == 0 ){
console.log("no files selected");
}

Validating user input using javascript

I'm trying to validate what a user enters into a texbox on the client-side, using javascript. I have also added a span close to my input tag like so,
<div>
<label for="fname">First Name*</label>
<input id="fname" name="fname" maxlength="30" type="text" /><span style="display:none;" id="fnameerror" name="fnameerror">*Please enter your firstname</span>
</div>
Here's the javascript code snippet validating the input,
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
}
What I want to achieve now is,
1) The textbox with the error should gain focus.
2) After the error message is displayed and the user enters a valid data, the error message should disappear.
How do I achieve this. I'm fairly new to javascript. Thanks.
Change your JS code:
document.getElementById('fname').onkeyup = function() {
if(document.getElementById('fname').value.length==0){
msg='Please enter your first name';
document.getElementById('fnameerror').style.display='inline';
document.getElementById('fnameerror').style.color='red';
valid=false;
document.getElementById('fname').focus();
} else {
valid=true;
document.getElementById('fnameerror').style.display='none';
}
}
Fiddle.
If you've read about HTML5, it allows you to add form validation as attribute fields directly instead of having to write code for it. It also presents things neatly. Have a look. This might help:
http://diveintohtml5.info/forms.html
I will suggest to use Jquery validator. Of course you need to include jquery,and jquery plugin, but you do not need time to write validation from the scratch only to implement what exist.

How to validate that input in textbox follows certain format

I am trying to code a page to lookup tickets in our system. All tickets follow the following format (6 digits, the dash, followed by 6 more digits):
123456-789123
I have created an HTML form to ask for and redirect the user to the results:
<section class="is-search">
<form method="get" action="http://mytesturl.com/tickets/lookup/info.php">
<input type="text" class="text" name="ticket" placeholder="Search by Ticket #" />
</form>
</section>
Currently, if someone types in "potato", the form will submit and throw several errors as the API obviously cannot search on "potato" or anything else that does not follow the ticket format.
I have seen a few recommendations on using JavaScript, however, I have not been able to get my syntax correct for the ticket format and was curious if there was a better way to do this in PHP as I am not familiar with JS.
What would be the best way to verify that the input follows this format before submitting to the API?
Have you tried using regular expression(regex).
This might help...
http://php.net/manual/en/function.preg-match.php
Use regular expression to check the format right before you submit the form
//on click, when the form is about to be submitted
$("#submit").click(function (e){
//prevent the submission unlit we check for valid format
e.preventDefault();
//check for valid format using regular expression test
if(/([0-9]{6}\-[0-9]{6})/.test($("input[name=ticket]").val())){
//submit
$("#search-form").submit();
}
else{
//display error
alert("error");
$("input[name=ticket]").val("");
}
});
HERE IS AN EXAMPLE
Regular expressions should work for this, both in javascript and PHP, something like :
$('.text').on('change', function() {
if (this.value.match(/^[0-9]{6}\-[0-9]{6}$/)) {
alert('ok');
}else{
alert('not valid');
}
});
FIDDLE
As noted by Jason in the comments, javascript validation is for convenience only, and any user input should be validated again on the serverside.
EDIT:
If for some reason you need the validation part as well ?
$('.is-search form').on('submit', function(e) {
e.preventDefault();
if ($('.text', this).val().match(/^[0-9]{6}\-[0-9]{6}$/)) {
this.submit();
}else{
alert('not a valid ticket number')
}
});
FIDDLE
You can start with adding the HTML attribute pattern="\d{6}\-\d{6} into the input tag. Then consider adding JavaScript checks, to cover browsers that do not support pattern but have JavaScript enabled.
<input type="text" class="text" name="ticket" placeholder="Search by Ticket #" onchange="myFunction()" />
myFunction(){
var value = $(".text").val();
if (/([0-9]{6}\-[0-9]{6})/.test(value)) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
}
<?php
if (preg_match('/([0-9]{6}\-[0-9]{6})/', &_POST['ticket'])) {
//execute code
}

How to validate form fields in a facebox?

I need to validate my form fields displayed in facebox.
The problem is that i am unable to get the values of the fields by using javascript.
for ex: document.form.field_name.value doesnt return its value.
Code sample :
<script type="text/javascript">
function validate()
{
if (document.form1.field.value=='')
{
alert ("Field cannot be left blank");
}
}
</script>
<form name="form1" onsubmit="return validate()">
<input type="text" name="field" />
</form>
A way to do this would be to pass the value directly from the form to the validation code.
<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" />
</form>
Or you could even use a text box without the form using:
<input type="text" id="field"
onkeydown="if (event.keyCode == 13) return validate(this.value)" />
Update the script to allow for the new value parameter:
<script type="text/javascript">
function validate(val) {
if (val.length < 1)
{
alert ("field cannot be left blank");
return false; //to stop the default action of submitting the form
} else {
alert ("Value: "+val);
return true; //allow to submit the page
}
}
</script>
This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.
I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.
NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.
Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...
This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.

Get files from input.files instead of value on submit

I have following problem. I have input field in form, type of file:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
I am setting using JavaScript also files property of this input and I want this input on submit of form send the file property instead of his value. Is it possible to do so?
var data = e.dataTransfer;
var input = dojo.byId(inputName);
var file = data.files[i];
input.files[0] = file;
data is a datatransfer object, I am getting files from there.
I know, it will be possible only in few browsers, I dont care. I just need to get it working at least in FF.
So if I understand you correctly you drop some files and you want to populate a file input object
I see a drop example here http://help.dottoro.com/ljslrhdh.php
but to populate the file field you will need a pretty heavy privilege change using a signed script - UniversalFileRead is probably the one you need

Categories

Resources