Allow empty string with regex - javascript

I'm trying to check if there's a number in a text input using regular expression. Here's the code:
var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input? I don't want to allow spaces, but I want to allow an empty input.
I tried:
var regex = /\s ^[0-9]+$/;
But then whatever I insert in the input, I always get "bad".

This might fit , either you test for your Exp (^[a-zA-Z0-9]+$) or for an empty string (^$).
var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}

try this (* in place of +)
var regex = /^[0-9]*$/;
if (myInput.val().test(regex)) {
console.log("number");
} else {
console.log("bad");
}

Related

how to prevent adding scripts in input fields

I need to prevent adding scripts inside input fields.is there any way to prevent adding javascript codes in text fields/text areas?
function filter($event) {
var regex = /[^a-zA-Z0-9_]/;
let match = regex.exec($event.target.value);
console.log(match);
if (match) {
$event.preventDefault();
} else {
return true;
}
}
You can sanitize the input by defining the blacklist regex which contains the patterns not allowed by the input and then replaced the part of input string with empty string if matched with the blacklist regex.
For now I just added a simple blackList regex (You can modify it as per your requirement) which will replace all the text comes between < and >. For Ex: If user enter <script>Hello</script> (This whole input text will get replaced with the empty string on keyup event.
const blackList = /<+>/ig
function sanitizeInput() {
const inputStr = document.getElementById('inputStr').value;
console.log('inputStr', inputStr)
document.getElementById('result').innerHTML = inputStr?.replace(blackList, '')
}
<input type="text" id="inputStr" onkeyup="sanitizeInput()"/>
<div id="result"></div>

Remove special character from the starting of a string and search # symbol.in javascript

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

Javascript IndexOf with integers in string not working

Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox

alphanumeric regex javascript

I am having a problem to get the simple reges for alphanumeric chars only work in javascript :
var validateCustomArea = function () {
cString = customArea.val();
var patt=/[0-9a-zA-Z]/;
if(patt.test(cString)){
console.log("valid");
}else{
console.log("invalid");
}
}
I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string
This regex:
/[0-9a-zA-Z]/
will match any string that contains at least one alphanumeric character. I think you're looking for this:
/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */
Or possibly this:
var string = $.trim(customArea.val());
var patt = /[^0-9a-z]/i;
if(patt.test(string))
console.log('invalid');
else
console.log('valid');
Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.
I fixed it this way
var validateCustomArea = function () {
cString = customArea.val();
console.log(cString)
var patt=/[^0-9a-zA-Z]/
if(!cString.match(patt)){
console.log("valid");
}else{
console.log("invalid");
}
}
I needed to negate the regex

Javascript function: caps after comma

I am trying to create a function that onkeydown(), forces all letters to be capitalized after a comma (",") in a text input field.
I know that I can make all of the letters capital using this function:
function makeUppercase(field) {
field.value = field.value.toUpperCase();
}
But am not sure how to say to do this function only after a comma is present.
regexps are good for things like that. something like
function makeUpperCaseAfterCommas(str) {
return str.replace(/,\s*([a-z])/g, function(d,e) { return ", "+e.toUpperCase() });
}
I suppose one way to do it would be to do a test:
if (field.value.indexOf(',') == -1) // comma doesn't exist in the string
{
// add the character
}
else
{
// add the uppercase version of the character.
}
You could test for commas and if they exist split on comma. Anything after the first index of the new array apply the toUppercase to and then rejoin the string on comma and replace the input field with the reformed string.
function makeUppercase(field) {
if(filed.value.indexOf(",") != -1)
{
var inputStr = field.value.split(",");
for(var i = 1; i < inputStr.length; i++)
{
inputStr[i] = inputStr[i].toUpperCase();
}
field.value = inputStr.join(",");
}
}

Categories