Limit select2 to only accept email addresses - javascript

I have a select2 box, an I was to limit this to accept only email addresses.
I am trying to do this by writing a custom formatSelection function, as
formatSelection: function(object, container){
if(validateEmail(object.text)){
return object.text;
}
else{
return "";
}
}
I am expecting that returning an empty string would be enough to not show this input in select2, but I am getting an empty result.

As of select2 4.0 +, just use the createTag function:
createTag: function(term, data) {
var value = term.term;
if(validateEmail(value)) {
return {
id: value,
text: value
};
}
return null;
}
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);
}

I have solved this. Just copy paste the code below and it will work smooth.
validate: function(value) {
if(value && value.length != 0){
var emailText = "";
var isValidEmail = true;
var isEmailLengthValid = true;
for (var i in value) {
var email = value[i];
isValidEmail = validateEmail(email);
if(isValidEmail == false){
break;
}else{
emailText = (i == 0) ? emailText : ", " + emailText;
if(emailText.length > 250){
isEmailLengthNotValid = false;
break;
}
}
}
if(isValidEmail == false){
return 'Enter a valid email address';
}else if(isEmailLengthValid == false){
return 'Maximum 250 characters allowed';
}
}
}
Also add below function validateEmail() which uses regex to validate email string.
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);
}

it isn't clear from your question where your data source is. if the data source is from an ajax call then you can do server side validation and only return the email addresses.
but i suspect that you want to accept user input and only of valid email addresses. The Select2 docs explain the createSearchChoice function in the initialization $opts. you could insert your validateEmail function here and decide if you want to accept the new answer or not.
you might even want to write to an external DOM element any errors you find so the user knows they have to go back and correct the invalid email address.
//Allow manually entered text in drop down.
createSearchChoice: function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {id:term, text:term};
}
},

i use select2 4.01
regex validator email
function isEmail(myVar){
var regEmail = new RegExp('^[0-9a-z._-]+#{1}[0-9a-z.-]{2,}[.]{1}[a-z]{2,5}$','i');
return regEmail.test(myVar);
}
i return only a text without id in the return json if it's no valid. in this cas, you can add alert no selectable.
createTag: function (params)
{
if(!isEmail(params.term)){
return {
text: params.term,
};
}
return {
id: params.term,
text: params.term,
};
}
In your templateResult
function formatRepoReceiver (repo) {
if (repo.loading) return repo.text;
var markup = "";
if(typeof(repo.email) == 'undefined'){
// >>>your Alert<<<<
if(!isEmail(repo.text)){
if(repo.text == ''){
return null;
}
return 'Address email no valid';
}
//----------------------------
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.text +"</span> "+
"(<span>" + repo.text + "</span>)"+
"</div>"+
"</div";
}
else{
markup = "<div class='select2-result-repository clearfix'>"+
"<div class='select2-result-repository__meta'>" +
"<span>"+ repo.name +"</span> "+
"(<span>" + repo.email + "</span>)"+
"</div>"+
"</div";
}
return markup;
}

$('.select2-tokenizer').on('change', function() {
var num= this.value
if(!$.isNumeric(num)){
$('option:selected',this).remove();
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Please enter an integer!'
})
}
});

Related

Problem in saving the value of an object key

Modify insert and remove to only work if the safe is opened, if the safe is closed then return Please open the safe first.
So all of my test cases are working properly, however I want to be able to do the following:
after removing an element via the remove method I want to access the element size value first
save it, then remove that element so that I can give the removed size back to the safe.
I tried doing it myself but I dunno how to code it, any suggestions?
class Safe {
constructor(safeSize, passcode) {
this.storage = [];
this.safeSize = safeSize;
this.oldSafeSize = this.safeSize;
this.passcode = passcode; // <---- Modify Safe to have a passcode attribute
this.isOpen = this.isOpen; // <---- Add isOpen attribute to the Safe Class
}
insert(name, size) {
//add restriction for insert to only work if this.isopen == true
if (this.isOpen == true) {
if (this.safeSize - size >= 0) {
this.safeSize -= size;
this.storage.push({
name,
size
}); // push it as an object
return true + " still accepting";
}
return false + " size limit reached";
} //end of isOpen tesecase
return "Please open the safe first"
}
remove(test) {
if (this.isOpen == true) {
let shouldSkip = false;
let message = "";
this.storage = this.storage.filter(element => {
if (element.name == test && !shouldSkip) {
// let temporarySize= this.safeSize;
shouldSkip = true;
this.storage.pop(element);
//adding the size back to the main safe only after
//deleting an element
// this.safeSize = this.oldSafeSize - temporarySize;
message = "The item " + element.name + " Has been removed"
return false;
}
return true;
});
if (!shouldSkip) message = test + " Item not found";
return message;
}
return "Please open the safe first"
}
setPassCode(passWord) {
if (this.passcode == undefined) {
this.passcode = passWord;
return "Passcode has been set"
}
return "please reset passcode first" // todo make a reset password function
}
resetPassCode(providedPasscode) {
if (this.passcode == undefined) {
return "Set a passcode first"
}
if (providedPasscode == this.passcode) {
this.passcode = undefined
return "Passcode has been reset"
}
return "Wrong passcode" // or this.passcode != providedPasscode
}
openSafe(testCode) {
if (this.passcode == testCode) {
this.isOpen = true
return "The safe is open and ready to use"
}
return "Wrong safe passcode"
}
closeSafe() {
this.Open = false;
return "The safe is closed"
}
} // end of class
const safe = new Safe(10);
testcases:
safe.setPassCode("8642"); // => "Passcode has been set"
safe.insert("laptop", 8); // => "Please open the safe first"
safe.remove("laptop"); // => "Please open the safe first"
safe.openSafe("7531"); // => "Wrong passcode"
safe.openSafe("8642"); // => "The safe is open and ready to use"
safe.insert("watermelon", 7); // => true
safe.remove("watermelon"); // => {name: "watermelon", "size: 7"}
safe.closeSafe(); // => "The safe is closed"
safe.insert("watermelon", 7); // => "Please open the safe first"
I've just found one typo.
closeSafe() {
// this.Open = false;
this.isOpen = false;
return "The safe is closed";
}
remove(test) {
if (this.isOpen == true) {
let shouldSkip = false;
let message = "";
this.storage = this.storage.filter(element => {
if (element.name == test && !shouldSkip) {
this.safeSize += element.size; // you've done similar job in insert method
shouldSkip = true;
this.storage.pop(element);
//adding the size back to the main safe only after
//deleting an element
// this.safeSize = this.oldSafeSize - temporarySize;
message = "The item " + element.name + " Has been removed"
return false;
}
return true;
});
if (!shouldSkip) message = test + " Item not found";
return message;
}
return "Please open the safe first"
}
Get the element size and subtract it from the safeSize.

How do I set a javascript variable inside a for loop to be used afterwards

So, I'm creating a login form, and when certain criteria aren't met to continue after the form, I am setting a variable to be tested after I've tested all the criteria. IF that variable ($cantcontinue) is set to 'true' I want to send a console message with the criteria that isn't met. Here is my code:
function testfields() {
// Ask if logging in or Creating Account
//Logging In:
if (document.getElementById("tEmail").style.display != "unset") {
var loginelements = ["Username", "Password"];
var text = "";
var i;
for (i = 0; i < loginelements.length; i++) {
//Check all fields are full:
if (document.getElementById(loginelements[i]).value == "") {
document.getElementById(loginelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(loginelements[i] + " is not set,")
} else {
document.getElementById(loginelements[i]).style.background = '#f7f7f7'
}
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
//Create a new Account:
} else {
var createelements = ["Username", "Password", "tEmaili", "tConfirmi"];
var text = "";
var i;
for (i = 0; i < createelements.length; i++) {
//Check all fields are full:
if (document.getElementById(createelements[i]).value == "") {
document.getElementById(createelements[i]).style.background = '#ff6060'
var cantcontinue = true;
console.log(createelements[i] + " is not set,")
} else {
document.getElementById(createelements[i]).style.background = '#f7f7f7'
}
}
//If passwords Match
if (document.getElementById("Password").value != document.getElementById("tConfirmi").value) {
var cantcontinue = true;
document.getElementById("tConfirmi").style.background = '#ff6060'
document.getElementById("tConfirmi").value = ''
console.log(" Passwords didn't Match,");
}
if ($cantcontinue != true) {
console.log("Create Account")
} else {
console.log("Could Not Create Account")
}
}
}
$cantcontinue !== cantcontinue;//....
Also
if (cantcontinue != true) {
equals:
if (!cantcontinue) {
Sidenote: Please don't use "$" unless you're using jQuery. It reminds me of PHP ( brrrrr...)

Form validation JavaScript not working

My form validation function is not working properly. The error msg displayed in the innerHTML element goes away as soon as it appears, like the page is being refreshed.I am new in javascript. I don't know whet seems to be the problem.
<script type="text/javascript">
function validate(form) {
var user = form.txtUsername;
var institute = form.txtinstitute;
var email = form.txtemail;
var pass1 = form.pwdpassword1;
var pass2 = form.pwdpassword2;
var check = "";
check = validateFilled(pass2);
check = validateFilled(pass1);
check = validateFilled(email);
if (check == true) {
check = validateEmail(email);
}
check = validateFilled(institute);
check = validateFilled(user);
if (checked == false) {
return false;
}
//return true;
}
function validateFilled(control) {
if (control.value.length == 0) {
document.getElementById(control.id).nextSibling.innerHTML = "* required";
document.getElementById(control.id).focus();
return false;
}
return true;
}
function validateEmail(control) {
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,}))$/;
if (!(re.test(email.value))) {
document.getElementById(email.id).nextSibling.innerHTML = " *invalid email";
document.getElementById(email.id).focus();
return false;
}
return true;
}
</script>
check = validateFilled(pass2);
check = validateFilled(pass1); //overrides check above
check = validateFilled(email); //overrides check above
if (check == true) {
check = validateEmail(email);//overrides check above
}
if (check == true) {
check = validateEmail(email);//overrides check above
}
check = validateFilled(institute);//overrides check above
check = validateFilled(user);//overrides check above
So if any of those are false, the other checks under it will make it true. Bad design....
You need to only set check to false if the validation fails....

put javascript variable into array and do foreach loop

I assigned a lot of variable in javascript and i wish to store these into array and do the looping like foreach in javascript. How should I do this?
var name=document.forms["form"]["name"].value;
var email=document.forms["form"]["email"].value;
var mobile=document.forms["form"]["mobile"].value;
var q1=document.forms["form"]["q1"].value;
var q2=document.forms["form"]["q2"].value;
var q3=document.forms["form"]["q3"].value;
var l1=document.forms["form"]["logo1"].value;
var l2=document.forms["form"]["logo2"].value;
var l3=document.forms["form"]["logo3"].value;
var p1=document.forms["form"]["photo1"].value;
var p2=document.forms["form"]["photo2"].value;
var p3=document.forms["form"]["photo3"].value;
if ( name == "" ) {
alert("Please fill up all field to submit!");
$('#name_error').css({'display': 'block'});
return false;
} else if ( email == "" ) {
alert("Please fill up all field to submit!");
$('#email_error').css({'display': 'block'});
return false;
}
This might do what you want?
var array = [];
array.push({ name: "name", value: document.forms["form"]["name"].value});
array.push({ name: "email", value: document.forms["form"]["email"].value});
array.push({ name: "mobile", value: document.forms["form"]["mobile"].value});
// add other values here ...
array.forEach(function (obj) {
if (obj.value == "") {
alert("Please fill up all field to submit!");
$("#" + obj.name + "_error").css({ "display": "block" });
return false;
}
});
Unfortunately, we need to store the name of the element in addition to its value in the array, so we can access the right error-element for it.
You could take a look at http://jqueryvalidation.org/ for validation
EDIT:
// I think we only need the element names and then get the value in the loop
var array = [];
array.push("name");
array.push("email");
array.push("mobile");
// add other values here ...
array.forEach(function (name) {
if (document.forms["form"][name].value == "") {
alert("Please fill up all field to submit!");
$("#" + name + "_error").css({ "display": "block" });
return false;
}
});
EDIT 2:
According to rene's comment:
If the function returns false, there should be no submit.
Hope i did everything alright this time ;)
$("#form").on("click", "#submitbutton", function(e) {
e.preventDefault();
var submit = true,
array = [];
array.push("name");
array.push("email");
array.push("mobile");
// add other values here ...
array.forEach(function (name) {
if (document.forms["form"][name].value == "") {
alert("Please fill up all field to submit!");
$("#" + name + "_error").css({ "display": "block" });
submit = false;
return false;
}
});
return submit;
});
I created a fiddle to show you how to do it: http://jsfiddle.net/markus_b/rtRV3/
HTML:
<form name="form">
<input type="text" name="name"/>
<input type="text" name="email"/>
<input type="text" name="mobile"/>
</form>
JS:
for (var i = 0; i < document.forms["form"].length;i++) {
if (document.forms["form"][i].value == "")
alert(document.forms["form"][i].name + " is empty!");
}
Basically you step through all the elements and query if they are empty.
This will create an object you could loop through
var values = {
name: document.forms["form"]["name"].value,
email: document.forms["form"]["email"].value,
mobile: document.forms["form"]["mobile"].value,
q1: document.forms["form"]["q1"].value,
q2: document.forms["form"]["q2"].value,
q3: document.forms["form"]["q3"].value,
l1: document.forms["form"]["logo1"].value,
l2: document.forms["form"]["logo2"].value,
l3: document.forms["form"]["logo3"].value,
p1: document.forms["form"]["photo1"].value,
p2: document.forms["form"]["photo2"].value,
p3: document.forms["form"]["photo3"].value
};
for ( var item in values ) {
console.log( item + ': ' + values[ item ];
// do something
}
if ( values.email === '' ) {
// conditional use here
}
var a = 1;
var all = new Array();
for(i=0;i<4;i++)
{
all[i]=a;
a++;
}
Replace 4 with number of fields and a with your document.get
Similarly you can access them.

why the javascript variable doesn't change among function?

my problem with the following javascript function:
function ValidateDates() {
var valid = false;
birthD = $("#cp1_txtBirthDate").val();
initialD = $("#cp1_txtInitialDate").val();
var regexp = new RegExp("^([1-9]|(0|1|2)[0-9]|30)(/)([1-9]|1[0-2]|0[1-9])(/)((20|19|18)[0-9]{2})$");
if (birthD != "__/__/____" && initialD != "__/__/____") {
if (regexp.test(initialD) && regexp.test(birthD)) {
$.get("ValidateDates.aspx?BirthD=" + birthD + "&InitialD=" + initialD, function (data) {
if (data == 0) {
valid = true;
$("#Dates_span").html("");
}
else {
$("#Dates_span").html("*" + data);
valid = false;
}
});
}
}
return valid;
}
here when i check the variable valid i found it "false" even if its true, because the initial for it is false from the beginning of function so how to solve it and what is wrong?
When you're doing an asynchronous call, you can't return a value like that. Instead, you should pass in a callback:
function ValidateDates(callback) {
var valid = false;
birthD = $("#cp1_txtBirthDate").val();
initialD = $("#cp1_txtInitialDate").val();
var regexp = new RegExp("^([1-9]|(0|1|2)[0-9]|30)(/)([1-9]|1[0-2]|0[1-9])(/)((20|19|18)[0-9]{2})$");
if (birthD != "__/__/____" && initialD != "__/__/____") {
if (regexp.test(initialD) && regexp.test(birthD)) {
$.get("ValidateDates.aspx?BirthD=" + birthD + "&InitialD=" + initialD, function(data) {
if (data == 0) {
valid = true;
$("#Dates_span").html("");
}
else {
$("#Dates_span").html("*" + data);
valid = false;
}
callback(valid);
});
}
}
}
Then, call it like:
ValidateDates(function(isValid)
{
// Do something with isValid
});
What's wrong is that $.get is an asynchronous call, what that means is that the function doesn't wait until the result is returned from $.get call. It just makes the call and continues execution - so valid = true is set long after false has been returned.

Categories

Resources