regex value check not working - javascript

Here is the page
If you select one of the 3 modems, it will open up the form below.
On the Billing > Address Line 1 field (left col), I'm trying to check for a PO Box entry and display a hidden message above the field. We're trying to discourage PO Box, but it should still allow submit, so I'm handling this separately from the jq val plugin on the form.
It's just not working, no matter what I try. The bind on the input is working, since it's logging properly, must be an issue with the regex, but I can't pinpoint it.
Here is the current js
var pobox = new RegExp('[PO.]*\\s?B(ox)?.*\\d+', 'i');
$("#bill_address1").bind("change paste keyup", function(){
if ($(this).val().match(pobox)) {
$('#pobox-warning').fadeIn(50);
console.log('box');
}
else {
$('#pobox-warning').fadeOut(50);
console.log('no box');
}
});
Any help would be appreciated - thanks!

It seems to me that a simple regex pattern like
/PO *Box/gi
would work best. Ignore case. Match the letters PO and any number of spaces followed by the word Box.
Edit:
Or to match the entire PO Box line with or without periods:
/P\.?O\.? *Box *\d*/gi

The initial part of your regular expression matches either a single "P", an "O", or a ".". You probably want something more like:
var pobox = /(P\.?O\.?)?\s*B(ox)?.*\d+/i;
It's much easier to use the native regular expression syntax in JavaScript when possible, as it appears to be in this case.

got it working with
var pattern = /^[P|p](OST|ost).*\s*[O|o|0](ffice|FFICE).*\s*[B|b][O|o|0][X|x]\s*(\d.)*/gi;
appreciate everyone's input

Related

Is it possible to have an emoji-only text input?

I'm building an Ionic2 app and one of my text fields needs to be an emoji-only field.. to make my situation a little harder, the input field can only be 1 emoji long.
From what I know of emojis, some are considered 2 characters, and some are 1, which makes me wonder how I can force only 1 emoji length in a text input.
Is this possible? Essentially just a text field that only accepts 1 emoji..
Any feedback would be great. Thank you!
Since you haven't yet provided your own code I'm not going to answer your whole question.
You could start off by using a regular expression that only allows characters and then modify it using something like the emoji regex library provided below.
var val = "🐬";
if (val.match(/[^a-zA-Z]/g)) { // NOTE: will also match only characters
console.log(val);
} else {
console.log("Only characters allowed.")
}
You could also try a library like the following that's a regular expression to match all Emoji-only symbols as per the Unicode Standard. https://mths.be/emoji-regex
There's also a great article on Optimizing RegEx for Emoji.

Regex to globally accept back space in javascript

I've got this regex that I'm using to restrict currency fields and it works great because I can simply replace the . with a , and I can easily localize it on the fly. My only issues is I can't seem to delete the last remaining character using this regex and I would like to be able to do that. is there a way to modify this regex to allow that?
^[+-]?([\b0-9])+[.]?([0-9])+$
EDIT: The regex above is being passed as a string through props in react to an input field. The input field is then checking this method before updating its value
matchRegex = (reg, val) => {
const regex = new RegExp(reg, "gm");
if (regex.test(val)) {
return true;
}
return false;
};
I was actually able to figure this one out. Since I'm intercepting the keystrokes, I actually don't need to worry about the whole string and can focus on one input character at a time so the following was able to meet my needs:
^([\b^0-9.-])*$

Javascript string validation. How to write a character only once in string and only in the start?

I am writing validation for phone numbers. I need to allow users to write + character only in the begining of input field and prevent users from writing it later in the field.
In other words:
+11111111 - right,
111111111 - right,
+111+111+ - false,
1111+111+ - false
The problem is that I need to perform validation while typing. As result I cannot analyse whole string after submision, thus it is not possible to fetch the position of + character because 'keyup' always returns 0.
I have tryed many approaches, this is one of them:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) {
// prevent from typing letters
$(this).val($(this).val().replace(/[^\d.+]/g, ''));
var textVal = $(this).val();
// check if + character occurs
if(textVal === '+'){
// remove + from occurring twice
// check if + character is not the first
if(textVal.indexOf('+') > 0){
var newValRem = textVal.replace(/\+/, '');
$(this).val(newValRem);
}
}
});
When I am trying to replace + character with empty string then it is replaced only once which is not enough, because user might type it a cople of times by mistake.
Here is the link to the fiddle: https://jsfiddle.net/johannesMt/rghLowxq/6/
Please give me any hint in this situation. Thanks!
To help you with the current code fix (#Thomas Mauduit-Blin is right that there are a lot more to do here than just allow plus symbol at the beginning only), you may remove any plus symbols that are preceded with any character. Just capture that character and restore with a backreference in the replacement pattern:
$(this).val($(this).val().replace(/[^\d.+]|(.)\++/g, '$1'));
See the updated fiddle and the regex demo.
The pattern is updated with a (.)\++ alternative. (.) captures any character but a newline into Group 1 that is followed with one or more plus symbols, and the contents of Group 1 is placed back during the replacement with the help of $1 backreference.
For better validation Why don't you use Jquery maskedinput library which will do lots of additional task for you without over head for other purpose also
$("#phone").mask("+999-999-9999");
$("#phone").mask("+9999-999-9999");
$("#phone").mask("+99999999999");
If you want to do the validation on your own, you must use a regex.
But, as described in another related thread here:
don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.
You must let the user enter an invalid phone number, and perform the check later, or on form submit and/or on server side for example. Here, you want to take care of the "+" character, but there are lot's of other stuff to do to have a trustable validation.
If your textVal has a +, indexOf will only check for the first occurence. You need to ensure that first character is not checked by indexOf. So use substring to take out first character from the equation.
Simply replace
if(textVal.indexOf('+') > 0){
with
if(textVal.substring(1).indexOf('+') > -1){
Demo

Jquery Validate Plugin to allow only text

I'm using following jquery plugin
http://digitalbush.com/projects/masked-input-plugin/
my current script is
<script type="text/javascript" charset="utf-8">
$(document).ready(function($) {
$("#answer55937X1X3othertext").mask("aaaaaaaaaaaaaaaaaaaaaaaaa",{ placeholder:"#" });
});
</script>
Problem:
But actually I would like to allow user to enter text only of any number of characters. Ex: words, Phrases or even sentences. So I figured regex would be good fit.
Question 1:
Any idea how to implement regex in this plugin ? If not please suggest alternative.Please include regex code too.
Question 2:(out of curiosity)
I did look at the website but couldn't find anything related to regex. Is regex by default included in plugins ? I don't know how to check whether that feature is included or not.
Thanks in advance
Update:
I tried below script but it is not working.
$('question'+QQ' input.text').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
as far as I know, you can't do that using 'masked input', it doesn't support the requirement you want.
it would perfactly fit for those input that having "fixed length", e.g.
an input with 8 length: 010-55555 (phone numbers)
an input with 8 or 11 length: 086-010-55555 (another phone numbers)
it does not support this:
this is a sentence that doesn't have fixed words.
Since it has to first of all fullfil the input with place holder "#".
If you want to validate the input, just write your own customized functions, using Really simple validations or other jquery validation frameworks, or even your own:
<input id="your_field" />
<script>
$("#your_field").blur(function(){
// your implementation here....
$(this).val().match(...)
})
</script>
Why do you need to use the mask plugin if you want to allow the user to enter whatever they want?
Besides, after looking at the page, it doesn't look like the plugin accepts regular expressions (please correct me if I'm wrong). For example, they use the * character to represent any alphanumeric character. In regular expressions, the * character has special meaning.
Hello fellow stackoverflower! I've just spent 20 minutes or so designing a jquery plugin that I'm hoping you, as well as many others, will be able to implement for this input masking. Please keep in mind, this is very quick work, and I hope to add to it, but just let me know if it fulfills your needs!
https://github.com/bmoyles0117/jQuery-SimpleMask
Please feel free to try to implement it using the code below, "a" stands for alphabetical, "#" stands for alphanumeric including spaces, and "9" of course stands for numbers. What I've done, is add flags to the initial config to say whether or not you'd like to allow periods, commas, or dashes. I really hope this fulfills your need!
<script src="jquery.simplemask.js"></script>
<script type="text/javascript">
$(function() {
$('#test123').simpleMask('aaaaa-####999', {
allow_periods : true,
allow_commas : true,
allow_dashes : true
});
});
</script>
<input type="text" id="test123" />

How to remove space and restrict special chars using jquery?

I am creating a signup form in my website. I want to implement some checkup with username, which are
username can't have any space,
username can't have any special characters other than dot (.) as gmail is doing in thier signup form.
I am using jQUERY in my app, can anyone tell me how to implement above listed two checkups using jquery ?? I remember these two main checkups for username please suggest if you knows any other?
Thanks
Have a look at the validation plug-in.
Whatever you do, validate the username at the server side too.
You can check that using javascript regex:
if ($('#username').val().match(/^(\w)+[\w\d\.]*/)) {
// everyting is ok
}else {
// something is wrong
}
First see here in another entry in SO, jquery-validate-how-to-add-a-rule-for-regular-expression-validation.
if you need other ideas try here for an example using PHP and an AJAX call using jQuery.
You can also check out this page for a another jQuery solution.
I tried out following jquery script by studying the links (this one) given by #Dror to check for wrong characters in username,
if (!$('#uname').val().match("^[a-z0-9'.\s]{1,50}$")) {
//not a correct username
}
Thanks
When I checked the answers, I saw that space is allowed. So I improve the regex for others that will read this question:
You need to do like this:
if (!$('#uname').val().match(/^[a-z0-9_-]{3,15}$/)) {
alert("Please, use standard characters.");
}
Description of regex:
^ -- Start of the line
[a-z0-9_-] -- Match characters and symbols in the list, a-z, 0-9,
underscore, hyphen
{3,15} -- Length at least 3 characters and maximum length of 15
$ -- End of the line

Categories

Resources