javascript: how to remove last entry? - javascript

Suppose i have the following JS code, i can only remove the whole characters whenever it receives non-acceptable character(s):
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
for (var i = 0; i < document.fr_upload.message.value.length; i++) {
if (!checkLatin(document.fr_upload.message.value)) {
alert("Your entry does not contain latin type.\n Please try again.")
document.fr_upload.message.value = '';
document.fr_upload.char_left.value = 0;
return false;
}
}
}
function checkLatin(arg) {
var latin = /^[\u0020-\u007E]*$/;
if (arg.match(latin)) {
return true;
} else {
return false;
}
}
Thus, how can i remove only non-acceptable character?

Try
function checkInput() {
document.getElementById("message").setAttribute('maxlength', (456));
var value = document.fr_upload.message.value;
if (value && !/[^\u0020-\u007E]/.test(value)) {
alert("Your entry contains non latin characters.\n Please try again.");
document.fr_upload.message.value = value.replace(
/[^\u0020-\u007E]/g, '');
document.fr_upload.char_left.value = document.fr_upload.message.value.length;
}
}

To replace the non-latin characters you can use:
function removeNonLatin(arg) {
var nonlatin = /!(^[\u0020-\u007E]*$)/g;
arg = arg.replace(nonlatin , '');
return arg;
}

Related

- using charAt I am trying to write a code which should display which word as unique character

i am new to js.
using charAt I am trying to write a code which should display which word as unique character.
i achieved using array https://jsfiddle.net/at661zsu/
but how to achieve using charAt.
providing code below
//var wholeWord = "pak";
var wholeWord = "pakk";
for(i=0; i<wholeWord.length; i++) {
var firsLoopCharacter = wholeWord.charAt(i);
var unique = true;
for(j=0; j<wholeWord.length; j++) {
var secondLoopCharacter = wholeWord.charAt(j);
if( i === j)
{
continue;
}
if( firsLoopCharacter === secondLoopCharacter[j] ) {
unique = false;
break;
}
}
}
if (unique) {
console.log("its an unique string");
}
else {
console.log("not unique string");
}
If you want to test if a string doesn't contain duplicate characters, here's a function that uses String.prototype.charAt():
function isUniqueCharsString(str) {
var chars = [];
for (var i = 0; i < str.length; i++) {
if(chars.indexOf(str.charAt(i))>=0){
return false;
}else{
chars.push(str.charAt(i));
}
}
return true;
}
It loops over the string characters and store unique charcters into a temporary array and test upon it.
Here's a Demo:
var wholeWord = "pak";
function isUniqueCharsString(str) {
var chars = [];
for (var i = 0; i < str.length; i++) {
if (chars.indexOf(str.charAt(i)) >= 0) {
return false;
} else {
chars.push(str.charAt(i));
}
}
return true;
}
console.log(isUniqueCharsString(wholeWord));

Javascript redirect URL

Below is a bit of script I'm using in related to a form for a site. I'm trying to get it to redirect to a specific page if the first two functions aren't valid.
What's happening is that the redirect is happening even if the functions are valid
I'm sure I'm missing something really simple here...
Any help appreciated!
(function(){
var f1 = fieldname2,
valid_pickup_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function (postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if( AND(f1,f2))
{
if( valid_pickup_postcode(f1) && valid_dropoff_postcode(f2))
{
return 'Please select the vehicle you require for your delivery';
}
else
{
return window.location.href = "http://www.bing.com";
}
}
else
{
return '';
}
})()
(function() {
var f1 = fieldname2,
valid_pickup_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
var f2 = fieldname7,
valid_dropoff_postcode = function(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
};
if (AND(f1, f2)) {
if (valid_pickup_postcode(f1) && valid_dropoff_postcode(f2)) {
return 'Please select the vehicle you require for your delivery';
} else {
// return window.location.href = "http://www.bing.com";
window.location.replace("http://www.bing.com");
}
} else {
return '';
}
})()
window.location.replace("http://www.bing.com"); should do the trick
Update: I have made small changes to make your code work. For something that's as straightforward as validating pickup and dropoff postal codes, the JS isn't (or shouldn't be) very complicated :) Here's a simpler version that will work
function myValidator(f1, f2) {
// Validate pickup postal code
function pickup_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[O,X]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
// Validate dropoff postal code
function dropoff_postcode(postcode) {
if (postcode) {
if (isNaN(postcode)) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
} else {
return false;
}
} else {
return false;
}
}
if (pickup_postcode(f1) === true && dropoff_postcode(f2) === true) { // If both pickup and dropoff postal codes are ok return a message prompting vehicle selection
return 'Please select the vehicle you require for your delivery';
} else { // Invalid pickup or dropoff postal code
// Redirect to website because either pickup or dropoff postal code is invalid
window.location.replace("https://www.bing.com");
}
}
myValidator("X909EF", "X909EE"); // Call it this way

Javascript: Problems with invoking functions within a function

I am trying to clean up this spaghettified code and I decided to separate the methods into separate functional objects and then call them within a single validate function. The code runs correctly on the first function and returns an alert box correctly. However, when I fix the first alert and resubmit the form the second function fires an alert at me to fix something, I click okay and immediately get an alert on the third function. Obviously I need to put in some code to stop the program from running after I click okay to the second functions alert so I can fix the issue, but how?
var checkboxes = document.getElementsByName('days');
var valid = false;
function textFieldValid(){
var textFieldsReq = document.getElementsByName('textFieldReq');
for( var i=0;i<9;i++ ){
if ( !textFieldsReq[i].value ){
alert ( 'You need to fill in the required* text field!' );
textFieldsReq[i].focus();
return false;
}
}
};
function checkboxesValid(){
for ( var i = 0;i<checkboxes.length;i++ ){
if ( checkboxes[i].checked ) {
valid = true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one day!' );
checkboxes[0].focus();
return false;
}
}
function lodgeValid(){
var lodging = document.getElementsByName('lodge');
for( var i=0; i<lodging.length; i++ ){
if( lodging[i].checked ){
valid=true;
break;
}
}
if ( !valid ) {
alert( 'You need to select at least one option!' );
lodging[0].focus();
return false;
}
}
function validate(textFieldsReq){
textFieldValid();
checkboxesValid();
lodgeValid();
};
You need to return true/false from each of the tests and then
var checkboxes = document.getElementsByName('days');
function textFieldValid() {
var textFieldsReq = document.getElementsByName('textFieldReq');
for (var i = 0; i < 9; i++) {
if (!textFieldsReq[i].value) {
alert('You need to fill in the required* text field!');
textFieldsReq[i].focus();
return false;
}
}
//if valid return true
return true;
};
function checkboxesValid() {
//create local variables
var valid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one day!');
checkboxes[0].focus();
return false;
}
//if valid return true
return valid;
}
function lodgeValid() {
var lodging = document.getElementsByName('lodge'),
valid = false;
for (var i = 0; i < lodging.length; i++) {
if (lodging[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one option!');
lodging[0].focus();
return false;
}
//if valid return true
return valid;
}
function validate(textFieldsReq) {
//check whether all the tests are turnig true
return textFieldValid() && checkboxesValid() && lodgeValid();
};

regex test alwayes returns false

$("#pincode").blur(function () {
var pincode = $("#pincode").val().trim();
var pattern = /^[0-9]{6}$/;
if (pincode != "" && !IsPatternFormate(pincode, pattern)) {
$("#pincode").addClass('invalidValidation');
document.getElementById('pincode')
.setCustomValidity('please enter data in proper formate');
}
});
var IsPatternFormate = function (value, pattern) {
var match = pattern.test($(value));
console.log(match);
}
i don't know why, match always return me false value.
var IsPatternFormate = function (value, pattern) {
if(pattern.test(value)){
return true;
}else{
false;
}
}
Change your IsPatternFormate function

Validate multiple emails with JavaScript

I have these two functions:
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
} else {
return true;
}
}
}
The problem is that when I test the email like this if(!self.validateEmails(multipleEmails)) { i get true or false based only on the first email in the string, but I want to test for any email in the string.
Thank you!
The problem is your if/else block; You are returning under both conditions. Which means that it leaves the function after evaluating only one element.
I've modified validateEmails to demonstrate what you probably want to do:
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
return false;
}
}
return true;
}
how about this?
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
var errors = [];
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
errors[i] = result[i] + ' is not valid.';
}
}
if (errors.length > 0) {
alert(errors.join('\n'));
return false;
} else {
return true;
}
}
in case you use jquery-validate the validation method would look like:
jQuery.validator.addMethod("separated_emails", function(value, element) {
if (this.optional(element)) {
return true;
}
var mails = value.split(/,|;/);
for(var i = 0; i < mails.length; i++) {
// taken from the jquery validation internals
if (!/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(mails[i])) {
return false;
}
}
return true;
}, "Please specify a email address or a comma separated list of addresses");
I find the most maintainable way is to use a variable to store the return output.
validateEmail: function(value) {
var regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return (regex.test(value)) ? true : false;
}
validateEmails: function(string) {
var self = shareEmail;
var result = string.replace(/\s/g, "").split(/,|;/);
var allOk = true;
for(var i = 0;i < result.length;i++) {
if(!self.validateEmail(result[i])) {
allOk = false;
}
}
return allOk;
}
This code below is perfect to validate multiple email addresses separated with comma or semicolon using JQuery:
var emailReg = new RegExp(/^([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+##[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
var emailText = $('#email').val();
if (!emailReg.test(emailText)) {
alert('Wrong Email Address\Addresses format! Please reEnter correct format');
return false;
}

Categories