mail validation with regex - regex

I want to make mail validation with regex but it's not working.where is my mistake?
It's normally working but when I put a regex control its never see yes the mail you key in is enable for this regex format.
Here is my code;
index.jsp
<head>
<title>Mail Control From Db</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="check.js"></script>
</head>
<body>
<div align="left">
<form name="chkForm" id="chkForm" method="post" >
<table>
<tr>
<td>Email</td>
<td>
<input type="text" name="email" id="email" size="20" ></td>
<td>
<div id="emailInfo" align="left"></div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
check.js
$(document).ready(function()
{
var myForm = $("#chkForm"), email = $("#email"), emailInfo = $("#emailInfo");
//send ajax request to check email
email.blur(function()
{
$.ajax({
type: "POST",
data: "email="+$(this).attr("value"),
url: "check.jsp",
beforeSend: function()
{
emailInfo.html("<font color='blue'>Kontrol Ediliyor..</font>");
},//end beforeSend: function()
success: function(data)
{
var reg = /\S+#\S+\.\S+/;
if (reg.test(email.val()))
{
var checkData = data.toString();
if(checkData == 0)
{
emailok = false;
emailInfo.html("<font color='red'>Mail in use</font>");
}//end if(checkData == 0)
else if(checkData == 1)
{
emailok = true;
emailInfo.html("<font color='green'>Mail is not in use</font>");
}//end else if(checkData == 1)
}//end if (reg.test(email.val()))
else
{
emailInfo.html("<font color='red'>ınvalid mail</font>");
}//end else
}// end success: function(data)
});
});//end email.blur(function()
});//end $(document).ready(function()
I had a problem in check.jsp. and solved it.
problem is about regex.Regex was false.
condition was false. i change it with if (reg.test(email.val())).

Your regex only allows capital letters, so TEXT#EXAMPLE.COM would be okay but test#example.com not. You can change that either by adding the case-insensitive-flag to your regex
/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$/i
or simply allow a-z in the regex itself
/^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/
But keep in mind that checking emails for validity is quite a difficult tasks to do, as the range of allowed mail-adresses is extremely broad and they even could contain special-chars like äüö etc. So your regex is not perfect, keep that in mind!
In PHP, I used this function for years and it always seemed to work.
Why exactly are you using .toString() in this case? .test() gives you an boolean which you can perfectly check with == false - is there any reason why you want to convert this to a string?

Related

Issue in regex in angular 13 cli

About
I am using Angular 13 CLI. There is input type textbox with validation to support only small and upper case characters but due to some reasons, it is allowing to accept other than letter also.
Component - Js
export class ProfileComponent implements OnInit {
public accountForm: any = null;
constructor() {
this.accountForm = new FormGroup({
first_name: new FormControl("", [
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern(/^[a-zA-Z]+$/)
])
});
}
ngOnInit(): void {
}
}
Html
<form [formGroup] = "accountForm">
<input type="text" formControlName="first_name" [value]="this.userData.first_name" />
<span *ngIf="this.accountForm.controls.first_name.errors && this.accountForm.controls.first_name.dirty ">
<ng-container *ngIf="this.accountForm.controls.first_name.errors.required; else second">
This is required
</ng-container>
<ng-template #second>
<ng-container *ngIf="this.accountForm.controls.first_name.errors.minlength; else third">
min length error
</ng-container>
</ng-template>
<ng-template #third>
<ng-container *ngIf="this.accountForm.controls.first_name.errors.maxlength; else fourth">
max length error
</ng-container>
</ng-template>
<ng-template #fourth>
<ng-container *ngIf="this.accountForm.controls.errors.pattern">
Invalid format for first name
</ng-container>
</ng-template>
</span>
<button>Submit</button>
</form>
Late for the answer.
You miss out on specifying the form control (first_name) for displaying the pattern error.
this.accountForm.controls.errors.pattern
It should be:
this.accountForm.controls.first_name.errors.pattern

How to submit a CFInput type=file within a CFDiv container

I am submitting a file in a cfdiv container, but the value of the file is not submitting to the processing page. If I submit the file outside of the cfdiv, it sees the file value. However, if the file is inside a cfdiv or div container, the form field is undefined. I have also added the enctype="multipart/form-data" to the cfform, but it is still not working.
UPDATE:
This is the first page (index.cfm)
<div name="loadcontainer" id="loadcontainer">
<cfinclude template="homepage.cfm">
</div>
The homepage.cfm
<cfform name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<cfinput size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</cfform>
When the save button is clicked, it doesn't see the form.school_logo value in the action processing page.
I have also tried using a normal form and input, instead of a cfform/cfinput, but the form is being loaded into another tab when submitted, instead of the div container.
"File" is an incorrect "type" for a CFINPUT in earlier CF Versions (not sure what version you are using). I did check the docs and it is allowed in current versions.
Meanwhile, Instead change your CFINPUT to:
<input size="50" type="file" id="school_logo" name="school_logo">
Or better yet, get rid of <cfform> - you aren't using it for anything and you don't need it. A good JS library (jquery) will provide you with better functionality for validation etc.
In this case you could easily do:
<form name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<input size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</form>
And it would work as expected. Cfform is designed to provide simple validation functions in a native CF Fashion, but outside of tutorials and books explaining CFML almost no one uses it. When we see it used here at CF Webtools, we refactor it as soon as we are able.
I was able to Submit the form both the <cfinput type="file"..../> and other form field in the form with ajax.
<script>
function validateForm() {
var x = document.forms["add_academic_year"]["start_year"].value;
var y = document.forms["add_academic_year"]["end_year"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Start Year and End Year Must be Selected");
return false;
}
if (y <= x) {
alert("End Year must be greater than Start Year ");
return false;
}
console.log("submit event");
var fd = new FormData(document.getElementById("add_academic_year"));
$.ajax({
url: "pro_academic_year.cfm",
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( response ) {
// display response in DIV
$("#loadcontainer").html( response.toString());
})
.fail(function(jqXHR, textStatus, errorMessage) {
// display error in DIV
$("#outputf").html(errorMessage);
})
return false;
}
</script>

Google places API only autocompletes street name field . . . but throws no errors

I'm new to Google's Places API. I'm trying to get a Django form to autocomplete, but for some reason, only one of the fields (Street 2) will autocomplete. The rest are just blank. And my console throws no errors, so I really have no idea what the issue is.
The other WEIRD thing . . . the inputs are holding the initial values that I passed to the form from the Django view even though the google autocomplete javascript has set them to "" before trying to autofill them. Is that normal?
Here's the HTML:
<div id="locationField">
<input id="autocomplete" name="search_address" onFocus="geolocate()" placeholder="Search for your address . . ." type="text" />
</div>
<hr class="hr-style">
<div >
<strong>Street</strong>
<input id="street_name" name="street" type="text" value="1030 E State Street" />
</div>
<div >
<strong>Street 2</strong>
<input id="route" name="street2" type="text" value="Apt. 2A" />
</div>
<div >
<strong>City</strong>
<input id="city" name="city" type="text" value="Los Angeles" />
</div>
<div class="6u 12u$(small) ">
<strong>State</strong>
<select id="state" name="state">
<!-- options removed for brevity's sake -->
</div>
<div class="6u 12u$(small) ">
<strong>Zip</strong>
<input id="zipcode" name="zipcode" type="text" value="90210" />
</div>
And the javascript, just copied from Google and modified with my input id's:
//geosearch powered by Google
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
$(function(){
initAutocomplete();
});
var placeSearch, autocomplete;
var componentForm = {
street_name: 'short_name',
route: 'long_name',
city: 'long_name',
state: 'short_name',
zipcode: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation
I'm thinking it has got to be failing somehow at this if statement in fillinAddress(), but I can't tell why:
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
Any help would be appreciated! And here's a screenshot of the form!
Turns out you can NOT rename the address form components. (I had renamed 'locality' to be 'city' and 'administrative_area_level_1' to be 'state.') I'm so new to this; I had no idea! I just thought that the variable names in the javascript had to match your input id's in your HTML. Turns out the address form components have to stay:
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'

How to add text input to dropzone upload

I'd like to allow users to submit a title for each file that is dragged into Dropzone that will be inputted into a text input. But i don't know how to add it. Everyone can help me?
This is my html code code
<form id="my-awesome-dropzone" class="dropzone">
<div class="dropzone-previews"></div> <!-- this is were the previews should be shown. -->
<!-- Now setup your input fields -->
<input type="email" name="username" id="username" />
<input type="password" name="password" id="password" />
<button type="submit">Submit data and files!</button>
</form>
And this is my script code
<script>
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "upload.php",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
maxFilesize:10,//MB
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
},
accept: function (file, done) {
//maybe do something here for showing a dialog or adding the fields to the preview?
},
addRemoveLinks: true
}
</script>
You can actually provide a template for Dropzone to render the image preview as well as any extra fields. In your case, I would suggest taking the default template or making your own, and simply adding the input field there:
<div class="dz-preview dz-file-preview">
<div class="dz-image"><img data-dz-thumbnail /></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size></span></div>
<div class="dz-filename"><span data-dz-name></span></div>
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<input type="text" placeholder="Title">
</div>
The full default preview template can be found in the source code of dropzone.js.
Then you can simply pass your custom template to Dropzone as a string for the previewTemplate key of the option parameters. For example:
var myDropzone = new Dropzone('#yourId', {
previewTemplate: "..."
});
As long as your element is a form, Dropzone will automatically include all inputs in the xhr request parameters.
I am doing something fairly similar. I accomplished it by just adding a modal dialog with jquery that opens when a file is added. Hope it helps.
this.on("addedfile", function() {
$("#dialog-form").dialog("open");
});
In my answer, substitute your "title" field for my "description" field.
Add input text or textarea to the preview template. For example:
<div class="table table-striped files" id="previews">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<p class="name" data-dz-name></p>
<input class="text" type="text" name="description" id="description" placeholder="Searchable Description">
</div> ... etc.
</div>
</div>
Then in the sending function, append the associated data:
myDropzone.on("sending", function(file, xhr, formData) {
// Get and pass description field data
var str = file.previewElement.querySelector("#description").value;
formData.append("description", str);
...
});
Finally, in the processing script that does the actual upload, receive the data from the POST:
$description = (isset($_POST['description']) && ($_POST['description'] <> 'undefined')) ? $_POST['description'] : '';
You may now store your description (or title or what have you) in a Database etc.
Hope this works for you. It was a son-of-a-gun to figure out.
This one is kind of hidden in the docs but the place to add additional data is in the "sending" event. The sending event is called just before each file is sent and gets the xhr object and the formData objects as second and third parameters, so you can modify them.
So basically you'll want to add those two additional params and then append the additional data inside "sending" function or in your case "sendingmultiple". You can use jQuery or just plain js to get the values. So it should look something like:
this.on("sendingmultiple", function(file, xhr, formData) {
//Add additional data to the upload
formData.append('username', $('#username').val());
formData.append('password', $('#password').val());
});
Here is my solution:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", {
url: 'yourUploader.php',
init: function () {
this.on(
"addedfile", function(file) {
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<input id='"+file.filename+"' type='text' name='caption' value="+caption+" >");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
}),
this.on(
"sending", function(file, xhr, formData){
formData.append('yourPostName',file._captionBox.value);
})
}
});
yourUploader.php :
<?php
// Your Dropzone file named
$myfileinfo = $_POST['yourPostName'];
// And your files in $_FILES
?>
$("#my-awesome-dropzone").dropzone({
url: "Enter your url",
uploadMultiple: true,
autoProcessQueue: false,
init: function () {
let totalFiles = 0,
completeFiles = 0;
this.on("addedfile", function (file) {
totalFiles += 1;
localStorage.setItem('totalItem',totalFiles);
caption = file.caption == undefined ? "" : file.caption;
file._captionLabel = Dropzone.createElement("<p>File Info:</p>")
file._captionBox = Dropzone.createElement("<textarea rows='4' cols='15' id='"+file.filename+"' name='caption' value="+caption+" ></textarea>");
file.previewElement.appendChild(file._captionLabel);
file.previewElement.appendChild(file._captionBox);
// this.autoProcessQueue = true;
});
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
const myDropzone = Dropzone.forElement(".dropzone");
myDropzone.processQueue();
});
this.on("sending", function(file, xhr, formData){
console.log('total files is '+localStorage.getItem('totalItem'));
formData.append('description[]',file._captionBox.value);
})
}
});
For those who want to keep the automatic and send datas (like an ID or something that does not depend on the user) you can just add a setTimeout to "addedfile":
myDropzone.on("addedfile", function(file) {
setTimeout(function(){
myDropzone.processQueue();
}, 10);
});
Well I found a solution for me and so I am going to write it down in the hope it might help other people also. The basic approach is to have an new input in the preview container and setting it via the css class if the file data is incoming by succeeding upload process or at init from existing files.
You have to integrate the following code in your one.. I just skipped some lines which might necessary for let it work.
photowolke = {
render_file:function(file)
{
caption = file.title == undefined ? "" : file.title;
file.previewElement.getElementsByClassName("title")[0].value = caption;
//change the name of the element even for sending with post later
file.previewElement.getElementsByClassName("title")[0].id = file.id + '_title';
file.previewElement.getElementsByClassName("title")[0].name = file.id + '_title';
},
init: function() {
$(document).ready(function() {
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
photowolke.myDropzone = new Dropzone("div#files_upload", {
init: function() {
thisDropzone = this;
this.on("success", function(file, responseText) {
//just copy the title from the response of the server
file.title=responseText.photo_title;
//and call with the "new" file the renderer function
photowolke.render_file(file);
});
this.on("addedfile", function(file) {
photowolke.render_file(file);
});
},
previewTemplate: previewTemplate,
});
//this is for loading from a local json to show existing files
$.each(photowolke.arr_photos, function(key, value) {
var mockFile = {
name: value.name,
size: value.size,
title: value.title,
id: value.id,
owner_id: value.owner_id
};
photowolke.myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
photowolke.myDropzone.emit("thumbnail", mockFile, value.path);
// Make sure that there is no progress bar, etc...
photowolke.myDropzone.emit("complete", mockFile);
});
});
},
};
And there is my template for the preview:
<div class="dropzone-previews" id="files_upload" name="files_upload">
<div id="template" class="file-row">
<!-- This is used as the file preview template -->
<div>
<span class="preview"><img data-dz-thumbnail width="150" /></span>
</div>
<div>
<input type="text" data-dz-title class="title" placeholder="title"/>
<p class="name" data-dz-name></p><p class="size" data-dz-size></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
</div>

Geocoder not working, cant get long and lat to display in alert box

I am new to javascript and geocoding and I'm trying to learn how to use the two together.
I have created a form to take the users input post code and I then have the code to convert it to long and lat. I have included and alert to show the postcode so as I know how much has worked (more to help me teach myself)
It returns the alert box with the input post code but nothing else!?
I would like it show the long and lat in alert box's. Once I know I have the long and lat I will be looking into adding them into a MySQL table, but I will worry about that once I know I have retreived the values
Here is the code:
<html>
<head>
<script type="text/javascript">
function getPostCode() {
var postcode = document.getElementById("pcode").value;
alert("Your Post Code is: " + postcode);
var gc = new google.maps.Geocoder();
gc.geocode({'address' : postcode}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
alert( "latitude : " + results[0].geometry.location.lat() );
alert( "longitude : " + results[0].geometry.location.lng() );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body>
<form name="search" METHOD="GET" onsubmit="return getPostCode()">
Post Code: <input type="text" name="pcode" />
<input type="submit" value="Search"/>
</form>
</body>
</html>
Any help would be much appreciated
----------------Update-------------------
Matt thanks for you help so far, I have now edited the code to output the value to paragraph tags and removed the alert box, but it still wont display the lat and long, is my geocode code correct? It pulls through the post code but not the lat and long or error.
<html>
<head>
<script type="text/javascript">
function getPostCode() {
var postcode = document.getElementById("pcode").value;
var postcode = "Your Post Code is: " + postcode;
document.getElementById("p1").innerHTML=postcode;
var mygc = new google.maps.Geocoder();
mygc.geocode({'address' : postcode}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
document.getElementById("lat").innerHTML=lat;
var lat = results[0].geometry.location.lng();
document.getElementById("long").innerHTML=long;
} else {
var err = "Geocode was not successful for the following reason: " + status;
document.getElementById("error").innerHTML=err;
}
});
}
</script>
</head>
<body>
<form name="search">
Post Code: <input type="text" name="pcode" />
<input type="button" value="Search" onclick="getPostCode()" />
</form>
<p id="p1"></p>
<p id="long"></p>
<p id="lat"></p>
<p id="error"></p>
</body>
</html>
I'm not 100% sure what you're doing since you say you're using v3 of the API but you don't need to construct google.maps.geocoder for v3 -- that's a version 2 thing. Besides that, you aren't even including Google's Javascript onto your page with a <script> tag. Look at your Javascript console. It's probably throwing an error.
To geocode with v3, just make requests to this URL, for example:
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
The response is ready-to-parse JSON. No need for classes, instantiation, etc.
Is that what you are trying to do?