Jquery Validate if field contains a comma - javascript

I have been looking around but can't find a way to do this. I really like the jquery validate script and I was wondering if there was a way to check to see if a field contains a comma and not validate if there is no comma.

You can use .inArray() method as it is described here
You should split your string, and then you can use this:
var found = $.inArray(',', categories)
if(found == -1) alert("Error!")

If you are referring to the jquery validate plugin:
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
$("#input").rules("add", { regex: "," })

not familiar with jquery validate but str.indexOf returns the position where something appears in a string, -1 means it doesnt. check a string for a comma like this :
if (yourString.indexOf(',') > -1) {
validate();
}

Related

Search for one or more characters and replace in JavaScript

By using indexOf() I was able to detect if the input contains "SP-" and replace.
However, I need to look for more than one set of characters:
sp-, SP-, eb-, EB- and more...
I have the following to replace sp- and SP- but I don't want to replicate this entire block for every instance.
// Check for 'sp-' characters in the order ID.
if (order_id.indexOf("SP-") !== -1) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace("SP-", ""));
}
// Check for 'SP-' characters in the order ID.
if (order_id.indexOf("sp-") !== -1) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace("sp-", ""));
}
Update - Just thought of a better solution, find all characters before and including - and remove it. So we're not limited to a specific list in case new prefixes are added at a later date.
sp-1234, SP-1234, xx-1234, etc.
To replace all case insensitive can you try this
form.find('input[name="orderid"]').val(order_id.replace(/sp-/gi, ''));
or you can do something like this
['SP-', 'sp-', 'eb-', 'EB-'].forEach((item)=>{
if ( order_id.indexOf(item) !== -1 ) {
// Remove string from input
form.find('input[name="orderid"]').val(order_id.replace(item, ''));
}
});
Update - Just thought of a better solution, find all characters before
and including - and remove it. So we're not limited to a specific list
in case new prefixes are added at a later date.
sp-1234, SP-1234, xx-1234, etc.
Maybe something like this should work
if(order_id.indexOf('-') !== -1) {
var prefix = order_id.substr(0, order_id.indexOf('-'));
form.find('input[name="orderid"]').val(order_id.replace(`${prefix}-`, ""));
}
Just use a regular expression with case insensitivity set. There is no reason to check for the string exists inside the string because the replace method does not do anything if there is no match.
function removePrefix(str) {
return str.replace(/(sp|eb)-/i, '');
}
["fo-foooo", "sp-123", "SP-123", "eb-321", "EB-911"].forEach( function (str) {
console.log(str, removePrefix(str));
});
Matching anything that starts with a string followed by a dash
function removePrefix(str) {
return str.replace(/^[^-]+-/i, '');
}
["fo-foooo", "sp-123", "SP-123", "eb-321", "EB-911"].forEach( function (str) {
console.log(str, removePrefix(str));
});
Try something like this:
var vals = ["sp-","ep-"] // Put all the values here
vals.forEach(v => {
if (order_id.indexOf(v) !== -1) {form.find('input[name="orderid"]').val(order_id.replace(v, ''))};
})

RegEx doesn´t work with Replace JavaScript Method

I need some help with Regular Expression, the problem is that I need apply the regex with Replace method in JavaScript. I saw a few post here in Stackoverflow but any regex doesn't works, I don't why.
I need that the user only can type in the input the following data:
100
100.2
100.23
Note: only number, it could be with one or two decimals maximum. Don't allow another symbols, and of course one comma.
I have been reading about it, and I used a few regex generator to see the match, so I made this one:
/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/
I got a little bit confused at the beginning because I used in the replace method:
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
And right now I read the process like: if I type a letter from a to z,the method will replace to space ''. but the rest doesn't works in the method but works in the generator for example.
Here is an example, you will see in the first input my regex vs Sven.hig regex:
const elementOne = document.getElementById('elementOne');
const elementTwo = document.getElementById('elementTwo');
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
elementTwo.addEventListener("input", function(event) {
this.value = this.value.replace(/^\d+[,]?\d{0,2}/, '');
});
<p>Element One (My RegEx)</p>
<input id="elementOne" type="text" />
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />
Also as a CodePen
Your regex is to match words not numbers you should replace [a-zA-Z]by [0-9] and the \. by \,
so your regex should look like this /^[0-9]+(\,[0-9]{0,2})?/
alternatively you could shorten the pattern /^\d+[,]?\d{0,2}/gm
here is code snippet to prevent user from entering words or any number that doesn't match the pattern
const elementTwo = document.getElementById('elementTwo');
var flag=false
elementTwo.addEventListener("input", function(event) {
pattern=/^\d+[,]?\d{0,2}$/
if (pattern.test(this.value)){
flag=true
l=this.value
if(flag&&this.value.length>1)
return this.value
else flag=false
}
else if(!pattern.test(this.value)&&flag==true){
return this.value=l
}
else if(!pattern.test(this.value)&&flag==false){
return this.value=""
}
});
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />
It looks like you're confusing a few things:
Replacing invalid characters in a string
Defining a validation pattern
Preventing entry of text
If your goal is to validate that your string has the correct format, you'd define a regular expression like:
const validFormat = /^\d+(,\d{0,2})?$/;
console.log(validFormat.test('99')); // true
console.log(validFormat.test('100,23')); // true
console.log(validFormat.test('X00,2E')); // false
console.log(validFormat.test('%#&SJ&#UJ')); // false
If your goal is to remove invalid characters (non-digits, non commas), you can define a regular expression for those invalid characters, but that's not the same thing as making sure your string now has a valid format. RegExp isn't able to do anything like that:
const invalidChars = /[^\d,]/g;
const sanitized = someString.replace(invalidChars, '');
If you want to prevent typing characters, you're better off adding a keydown event handler to your input and prevent the default behavior for invalid keys.
const myInput = document.querySelector('#some-input');
myInput.addEventListener('keydown', ({ key, preventDefault }) => {
if (key !== ',' && (key < '0' || key > '9')) {
preventDefault();
}
});

Is there a better way to implement "string contains substring" in javascript?

I am looking for better options in Javascript to check if a string contains a substring. Substring can either be a text from an input field or database.
Sample:
var substring = "DVI to VGA" //some code to get text from input field or database
var string = "12 DVI To VGA adapter"
if(string.toLowerCase().indexOf(substring.toLowerCase()) != -1){
//any action after match
console.log("FOUND A MATCH")
}
I can't think of any, but you can encapsulate what you have in a function that is more concise and reusable:
function stringContainsSubstring(string, substring) {
return string.toLowerCase().indexOf(substring.toLowerCase()) != -1;
}
var contains = (string.toLowerCase()).includes(substring.toLowerCase());
not exactly a solution, but you can use it like:
if(~string.toLowerCase().indexOf(substring.toLowerCase()){...
looks a bit cleaner

Checking for invalid characters from an input with jQuerys

I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.
Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters
Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.
This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}
Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}
If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

startswith in javascript error

I'm using startswith reg exp in Javascript
if ((words).match("^" + string))
but if I enter the characters like , ] [ \ /, Javascript throws an exception.
Any idea?
If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()
A better solution would be to use substr() like this:
if( str === words.substr( 0, str.length ) ) {
// match
}
or a solution using indexOf is a (which looks a bit cleaner):
if( 0 === words.indexOf( str ) ) {
// match
}
next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:
String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}
When added to the prototype you can use it like this:
words.startsWith( "word" );
One could also use indexOf to determine if the string begins with a fixed value:
str.indexOf(prefix) === 0
If you want to check if a string starts with a fixed value, you could also use substr:
words.substr(0, string.length) === string
If you really want to use regex you have to escape special characters in your string. PHP has a function for it but I don't know any for JavaScript. Try using following function that I found from [Snipplr][1]
function escapeRegEx(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
and use as
var mystring="Some text";
mystring=escapeRegEx(mystring);
If you only need to find strings starting with another string try following
String.prototype.startsWith=function(string) {
return this.indexOf(string) === 0;
}
and use as
var mystring="Some text";
alert(mystring.startsWith("Some"));

Categories

Resources