I have javascript code that will validate alphanumeric and dashes for any field it is assigned to. The regex completes successfully and the error message displays. What I would like to happen is upon hitting a key that would make the regex true it would delete the variable that set it to true (for example if someone where to hit the # key it would only delete the # character). Right now I have it set to erase the entire field.
function validateAlphaNumericField(field) {
var value = field.value;
var reg = /[^A-Za-z0-9-]/;
var newVal = reg.test(value)
if (newVal == true) {
alert("This field must contain only alphanumeric and dashes.");
field.value="";
}
}
you can replace the unexpected characters as following:
var value = field.value;
var reg = /[^A-Za-z0-9-]/;
return value.replace(reg,'');
Related
I have a function which autocompletes a username when they start typing with # (kind of like instagram)
When you type an # a list of users appears and the user can click on an item/user "ex: #User1" in the list and the script autocompletes the # with the username in the textarea "ex: #User1".
The first replacement goes wel "ex: #User1". But when the user types the second # (and not a first letter yet) and the list appears again and then clicks on a different item/user in the list, the chosen item/user "ex: #User2" gets added within the first # in front of the first suggestion "ex: #User2User1". But on the otherhand if the user types the second # WITH a first letter and THEN clicks on the item/user in the list the replacement goes well.
Link to codepen sample
this is my current function :
var string = $scope.searchParam;
var pattern = /#\b.+?\b/g;
$scope.match = string.match(pattern)
if($scope.match){
value = $scope.match.pop();
console.log('match')
}else{
console.log('was undefined');
var pattern = /#/g;
var found = string.match(pattern)
console.log(found +' is value');
if(found.length > 0){
value = found.pop();
}
}
string = string.replace(value, '#'+suggestion);
console.log('oke');
$scope.searchParam = string;
$scope.searchFilter = string;
i also tried to check if it was present allready to only trigger when a character is typed after the #sign with this:
if(watching && typeof $scope.searchParam !== 'undefined' && $scope.searchParam !== null) {
var string = $scope.searchParam;
var pattern = /#\b.+?\b/g;
$scope.match = string.match(pattern)
if($scope.match){
console.log($scope.match.length + 'match aantal' + $scope.i + ' i aantal');
$scope.matches.push($scope.match);
console.log($scope.matches);
var found = $filter('filter')($scope.matches,$scope.match,true)
if (!found.length) {
$scope.i++;
}
}
$scope.completing = true;
$scope.searchFilter = $scope.searchParam;
$scope.selectedIndex = -1;
}
but the matches are only a couple of letters so this array get's flooded. there are probably multiple answers to this problem and i'd like to know what you would go with in this situation.
The problem is in this line:
string = string.replace(value, '#'+suggestion);
If you only type # it will replace the first #. To avoid that, you have to match the last one:
string = string.replace(new RegExp(value+'$'), '#'+suggestion);
This will match the value only if it's at the end of the string, which is what you need.
You can check it on codepen.
I need to add validation to textbox and textarea to validate them against the following rules upon submit (ampersand and apostrophes are allowed). //,./,/.,/*,*.,~,\\
I tried the following code
alert("is valid "+ isValid("mhse sn hs ~"));
function isValid(value)
{
return !/[~//./*././*\\]/i.test(value);
}
the above code will return false because ~ is in this code but if i try / this will return false so i think problem in grouping characters.
1) write one javascript function which eliminates special charactors
function isValid(str){
var iChars = "#$%&"; // type your excepting keys here
var flag = true;
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
flag = false;
}
}
return flag;
}
2) check your entered value with isValid() function like below
isValid("hye!##~%^&*)");
Answer: if you entered special chars is there, then flag will returns false.
when you escape, you do it carefully :D
for matching * or . literally, you need to escape them
the corrected version will be
/[~/\/\.\/\*\./\.\/\*\\]/.test(".");
so i have this function that displays the inputted value of the user. I want to erase them all after clicking a specific button.
Here's the code:
HTML
<center> Are you sure you want to delete all?<br><br></center>
<div id="options11" onclick="EraseMe()"> Yes</div>
<div id="options12" onclick="CloseButton()">No</div>
JS:
function List(){
document.getElementById('order').innerHTML += document.getElementById('Name').value + document.getElementById('quan').value + parseInt(document.getElementById('Total').value);} //gets the inputted value of the user
function EraseMe(){
var name = document.getElementById('Name').value;
var quan = document.getElementById('quan').value;
var totals = document.getElementById('Total').value;
name.replace(/^[a-zA-Z0-9]$/, "");
quan.replace(/^[a-zA-Z0-9]$/, "");
totals.replace(/^[a-zA-Z0-9]$/, "");}
and also, i want to sum up all the value of the document.getElementById('Total') , but the result I'm having is a value of a string, not as an integer.
Here's the code for that:
function compute(){
totall = document.getElementById('quan') * document.getElementById('price');
document.getElementById('totalsss').value += parseInt(totall);
document.getElementById('totalsss').innerHTML = document.getElementById('totalsss').value;}
One problem, is that replace is a pure function and does not modify the input - as such, the result of String.replace must be used.
Another is the regular expression is anchored (meaning it would only match input of a single character in the given case), and yet another is the regular expression is not global (meaning it would only match once) ..
Try:
var nameElm = document.getElementById('Name');
// assign replacement result back to input's value,
// after substituting all (g) English alphabet characters/numbers
// with nothing .. any other characters will remain
nameElm.value = nameElm.value.replace(/[a-zA-Z0-9]/g, "");
If you want to blank something, just replace it with an empty string:
function EraseMe(){
document.getElementById('Name').value = "";
document.getElementById('quan').value = "";
document.getElementById('Total').value = "";
}
There's no reason to do that regex replacement unless there's something you want to keep.
I have several inputs in a form, but what I want to achieve is to send only the ones who have at least 1 character (alphanumeric), but for those who have empty or whitespace values must not be sent.
The problem is that when a user sends a whitespace by mistake by pressing the spacebar it serializes a plus sign (+).
So far this is what I do to send serialized non-empty values.
//this will print a query string with the values, but for whitespaces it sends '+' signs.
$('#myform').find('input').not('[value=""]').serialize();
You can use $.trim:
$('#myform').find('input').filter(function() {
return $.trim(this.value) != "";
}).serialize();
This will also take the actual user input (.value property) not the .defaultValue (value attribute) like .not('[value=""]')
You can do following:
var obj = {};
$('#myform').find('input').each(function() {
var value = $(this).val().trim();
var inputName = $(this).attr('name');
if(value.length != 0) {
obj[inputName] = value;
}
});
$(obj).serialize();
By Googling this seems to work pretty fine:
$('#myform').find('input:filled').serialize(),
reference:
http://jqueryvalidation.org/filled-selector/
I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps