First off, I am a complete noob. I have just recently started getting good with python and have close to zero knowledge regarding javascript and corvid for wix. I am looking through documentation but I can't figure out how to do the following: When a user fills out a field, let's say a phone number field, how do you validate whether that field has any alphabetical characters or "+" or "-" etc or not?
I am trying to do something like this:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
if( input1 is anything but an integer ) {
reject("Only Numbers. No '-', '.', '()', '+', or any alphabetical characters");
}
} );
});
I feel like I am close but have no idea. Any help is appreciated
To answer your question:
Includes Function
You would want to use the .includes() function native to javascript which returns a boolean of if it is or isn't included. If you need the string index of each occurrence you would need to use a for loop as shown below.
var string = "+54 2453-2534-242";
for(int i = 0; i < string.length(); i++){
if(string.substr(i,1) === "-"){
console.log(i);
}
}
Includes Function
Replace Function
Below is an example of how to use this function.
If you wish to remove these or one of these characters you can use the .replace() function or the .split() and .join() functions.
const string = "+53 573-2566-242";
const character_1 = "+";
const character_2= "-";
// Includes
console.log(string + ".includes(+):", string.includes(character_1));
console.log(string + ".includes(-):",string.includes(character_2));
// Replace Singular
var new_string = string.replace(character_1,'');
console.log(new_string);
// Replace Multiple
var new_string2 = string.split(character_2).join("");
console.log(new_string2);
Replace Funtion
If you are still stuck, please feel free to comment
Edit
To check if there are any alpha-numeric characters in a string. You can simply use the .replace() function and compare it. As seen below:
var string = "abc546"; // Your Phone Number Input
var string_converted = string.replace(/\D/g,'');
if(string !== string_converted){
console.log("Contains Characters that are not of type NUMBER!");
console.log(`${string} vs ${string_converted}`);
}
In your case, you could use the code below:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
// Assuing *value* is your input
var converted = value.replace(/\D/g,'');
if(value !== converted){
// Regective Statment Here..
}else{
// All good! (No Alph-numeric Characters)
}
});
});
Related
I need to change field dynamic and set format with this code i a formatting my zip code its text come from server end like
123456789
and this jQuery method change this value format
1234-56789
var ZIptext = $("#ZipLabel").text();
var reformat = ZIptext.replace(/(\d{5})/g, function (match) {
return match + "-";
});
$("#ZipLabel").text(reformat.replace(/\-$/, ""))
but know i am facing problem i need to change format of my fax number
3453454354
and it should be like
345-345-4354
So can someone help me
Do it with capturing group regex
var res = '3453454354'.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
document.write(res);
This question is similar to this one here.
You can do this using:
'345345345'.replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
Here's a function to do it generically.
The first argument is the input string, the second is the separator character, and the third is an array of lengths to separate the input with. You can specify a '*' as the last argument as well.
function separate(_input, _separator, _lengths) {
var output = [], i = 0;
for(i=0; i<_lengths.length; i++) {
if(_input.length <= _lengths[i] || _lengths[i] === '*') {
output.push(_input);
break;
}
output.push(_input.substr(0, _lengths[i]));
_input = _input.substr(_lengths[i]);
}
return output.join(_separator);
}
Usage examples:
separate('3453454354', '-', [3, 3, 4]); // returns "345-345-4354"
separate('3453454354', '-', [4,'*']); // returns "3453-454354"
I want to validate following text using regular expressions
integer(1..any)/'fs' or 'sf'/ + or - /integer(1..any)/(h) or (m) or (d)
samples :
1) 8fs+60h
2) 10sf-30m
3) 2fs+3h
3) 15sf-20m
i tried with this
function checkRegx(str,id){
var arr = strSplit(str);
var regx_FS =/\wFS\w|\d{0,9}\d[hmd]/gi;
for (var i in arr){
var str_ = arr[i];
console.log(str_);
var is_ok = str_.match(regx_FS);
var err_pos = str_.search(regx_FS);
if(is_ok){
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
}else{
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
but it is not working
please can any one help me to make this correct
This should do it:
/^[1-9]\d*(?:fs|sf)[-+][1-9]\d*[hmd]$/i
You were close, but you seem to be missing some basic regex comprehension.
First of all, the ^ and $ just make sure you're matching the entire string. Otherwise any junk before or after will count as valid.
The formation [1-9]\d* allows for any integer from 1 upwards (and any number of digits long).
(?:fs|sf) is an alternation (the ?: is to make the group non-capturing) to allow for both options.
[-+] and [hmd] are character classes allowing to match any one of the characters in there.
That final i allows the letters to be lowercase or uppercase.
I don't see how the expression you tried relates anyhow to the description you gave us. What you want is
/\d+(fs|sf)[+-]\d+[hmd]/
Since you seem to know a bit about regular expressions I won't give a step-by-step explanation :-)
If you need exclude zero from the "integer" matches, use [1-9]\d* instead. Not sure whether by "(1..any)" you meant the number of digits or the number itself.
Looking on the code, you
should not use for in enumerations on arrays
will need string start and end anchors to check whether _str exactly matches the regex (instead of only some part)
don't need the global flag on the regex
rather might use the RegExp test method than match - you don't need a result string but only whether it did match or not
are not using the err_pos variable anywhere, and it hardly will work with search
function checkRegx(str, id) {
var arr = strSplit(str);
var regx_FS = /^\d+(fs|sf)[+-]\d+[hmd]$/i;
for (var i=0; i<arr.length; i++) {
var str = arr[i];
console.log(str);
if (regx_FS.test(str) {
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
} else {
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
Btw, it would be better to separate the validation (regex, array split, iteration) from the output (id, jQuery, logs) into two functions.
Try something like this:
/^\d+(?:fs|sf)[-+]\d+[hmd]$/i
I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.
I'm definitely a newbie and am trying a practice project.
Its basically an anagram game where the user clicks on certain letters to put together a word.
I now need to check that it is actually a word. I've made a text file containing all the words in the dictionary (copied from someones website as its just a practice project). I've managed to get it so that if I can console.log the words.
function Searchtext(){
$.get('words.txt', function(data) {
console.log(data);
}, 'text');
}
Now I want to search the words to see if the player's answer ( a string which is declared in a variable called playeranswer ) is in the list. I don't need it to return the word, only whether it is there or not. N.B. it has to be exact so that for example if the user entered "ender" which isnt a word, it wont come back true because it finds the word "render". Maybe something with the .length will help?
How would I go about doing this?
Thanks for any help.
Since $.get is asynchronous, you'll have to set it up a little differently. I'd do this:
function Searchtext(name, callback) {
$.get('words.txt', function(data) {
data = data.split("\n");
var contains = (data.indexOf(name) > -1);
callback(contains);
}, 'text');
}
Depending on how the text file is setup, you might have to change .split("\n") (which splits up the words into an array, if they're each on a line) to .split(" ") (which splits up the words into an array, if they're separated by a space).
And you'd call it like:
SearchText(playername, function (matched) {
if (matched) {
// Name was in list
} else {
// Name wasn't in list
}
});
DEMO: http://jsfiddle.net/Fkr5B/
In the demo, I had to simulate the AJAX request.
I would use a regular expression (using a RegExp object) for this. Here is a simple example that tries to match a word in two different strings of words:
var word_to_match = 'ender';
var string_of_words = 'a string containing the word ender, this will match';
var second_string_of_words = 'a string that will not produce a match';
//use \b to match on word boundaries
var filter = new RegExp('\\b' + word_to_match + '\\b', 'gi');
if(string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
if(second_string_of_words.match(filter)) {
alert('found word: ' + word_to_match);
} else {
alert('did not find word: ' + word_to_match);
}
You'll see the first if statement passes, while the second fails. A little reading might be required, but you should be able to expand this example to fit your use case.
You should first parse the data variable and place the words into an Array.
Then you can test if the user entered a valid word by checking if your Array contains that word.
var Dict = new Array("render", "bender", "word");
function isValid(word){
if(Dict.indexOf(word) == -1)
return false; //the word is not valid
return true; //the word is valid
}
I've made this simple script, hope it helps
$(document).ready(function(e) {
function parseData(data) {
$('#inpu').blur(function() {
var str_to_search = $.trim($('#inpu').val());
if(str_to_search.length) {
var search_res = data.search(str_to_search);
if(search_res != -1) {
alert('Word Valid!');
} else {
alert('Word no valid');
}
}
});
}
$.get('to_search.txt', parseData).fail(function() { alert('error');});
});
I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&' instead of '&'), and then add a span around those entered entities.
How would I search through the string parameter to find this? Would it be a regex?
This is my code thus far:
function ampersandKiller(input) {
var specialCharacters = ['&', ' ']
if($(specialCharacters).contains('&')) {
alert('hey')
} else {
alert('nay')
}
}
Obviously this doesn't work. Does anyone have any ideas?
So if a string like My name is & was passed, it would render My name is <span>&</span>. If a special character was listed twice -- like 'I really like &&& it would just render the span around each element. The user must also be able to use the plain &.
function htmlEntityChecker(input) {
var characterArray = ['&', ' '];
$.each(characterArray, function(idx, ent) {
if (input.indexOf(ent) != -1) {
var re = new RegExp(ent, "g");
input = input.replace(re, '<span>' + ent + '</span>');
}
});
return input;
}
FIDDLE
You could use this regular expression to find and wrap the entities:
input.replace(/&| /g, '<span>$&</span>')
For any kind of entity, you could use this too:
input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span> <span><</span>
Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
function hasEntities(input) {
if (input.length != htmlDecode(input).length) {
return true;
}
return false;
}
alert(hasEntities('a'))
alert(hasEntities('&'))
The above will show two alerts. First false and then true.