Jquery Validate Plugin to allow only text - javascript

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" />

Related

Partial matching a string against a regex

Suppose that I have this regular expression: /abcd/
Suppose that I wanna check the user input against that regex and disallow entering invalid characters in the input. When user inputs "ab", it fails as an match for the regex, but I can't disallow entering "a" and then "b" as user can't enter all 4 characters at once (except for copy/paste). So what I need here is a partial match which checks if an incomplete string can be potentially a match for a regex.
Java has something for this purpose: .hitEnd() (described here http://glaforge.appspot.com/article/incomplete-string-regex-matching) python doesn't do it natively but has this package that does the job: https://pypi.python.org/pypi/regex.
I didn't find any solution for it in js. It's been asked years ago: Javascript RegEx partial match
and even before that: Check if string is a prefix of a Javascript RegExp
P.S. regex is custom, suppose that the user enters the regex herself and then tries to enter a text that matches that regex. The solution should be a general solution that works for regexes entered at runtime.
Looks like you're lucky, I've already implemented that stuff in JS (which works for most patterns - maybe that'll be enough for you). See my answer here. You'll also find a working demo there.
There's no need to duplicate the full code here, I'll just state the overall process:
Parse the input regex, and perform some replacements. There's no need for error handling as you can't have an invalid pattern in a RegExp object in JS.
Replace abc with (?:a|$)(?:b|$)(?:c|$)
Do the same for any "atoms". For instance, a character group [a-c] would become (?:[a-c]|$)
Keep anchors as-is
Keep negative lookaheads as-is
Had JavaScript have more advanced regex features, this transformation may not have been possible. But with its limited feature set, it can handle most input regexes. It will yield incorrect results on regex with backreferences though if your input string ends in the middle of a backreference match (like matching ^(\w+)\s+\1$ against hello hel).
As many have stated there is no standard library, fortunately I have written a Javascript implementation that does exactly what you require. With some minor limitation it works for regular expressions supported by Javascript.
see: incr-regex-package.
Further there is also a react component that uses this capability to provide some useful capabilities:
Check input as you type
Auto complete where possible
Make suggestions for possible input values
Demo of the capabilities Demo of use
I think that you have to have 2 regex one for typing /a?b?c?d?/ and one for testing at end while paste or leaving input /abcd/
This will test for valid phone number:
const input = document.getElementById('input')
let oldVal = ''
input.addEventListener('keyup', e => {
if (/^\d{0,3}-?\d{0,3}-?\d{0,3}$/.test(e.target.value)){
oldVal = e.target.value
} else {
e.target.value = oldVal
}
})
input.addEventListener('blur', e => {
console.log(/^\d{3}-?\d{3}-?\d{3}-?$/.test(e.target.value) ? 'valid' : 'not valid')
})
<input id="input">
And this is case for name surname
const input = document.getElementById('input')
let oldVal = ''
input.addEventListener('keyup', e => {
if (/^[A-Z]?[a-z]*\s*[A-Z]?[a-z]*$/.test(e.target.value)){
oldVal = e.target.value
} else {
e.target.value = oldVal
}
})
input.addEventListener('blur', e => {
console.log(/^[A-Z][a-z]+\s+[A-Z][a-z]+$/.test(e.target.value) ? 'valid' : 'not valid')
})
<input id="input">
This is the hard solution for those who think there's no solution at all: implement the python version (https://bitbucket.org/mrabarnett/mrab-regex/src/4600a157989dc1671e4415ebe57aac53cfda2d8a/regex_3/regex/_regex.c?at=default&fileviewer=file-view-default) in js. So it is possible. If someone has simpler answer he'll win the bounty.
Example using python module (regular expression with back reference):
$ pip install regex
$ python
>>> import regex
>>> regex.Regex(r'^(\w+)\s+\1$').fullmatch('abcd ab',partial=True)
<regex.Match object; span=(0, 7), match='abcd ab', partial=True>
You guys would probably find this page of interest:
(https://github.com/desertnet/pcre)
It was a valiant effort: make a WebAssembly implementation that would support PCRE. I'm still playing with it, but I suspect it's not practical. The WebAssembly binary weighs in at ~300K; and if your JS terminates unexpectedly, you can end up not destroying the module, and consequently leaking significant memory.
The bottom line is: this is clearly something the ECMAscript people should be formalizing, and browser manufacturers should be furnishing (kudos to the WebAssembly developer into possibly shaming them to get on the stick...)
I recently tried using the "pattern" attribute of an input[type='text'] element. I, like so many others, found it to be a letdown that it would not validate until a form was submitted. So a person would be wasting their time typing (or pasting...) numerous characters and jumping on to other fields, only to find out after a form submit that they had entered that field wrong. Ideally, I wanted it to validate field input immediately, as the user types each key (or at the time of a paste...)
The trick to doing a partial regex match (until the ECMAscript people and browser makers get it together with PCRE...) is to not only specify a pattern regex, but associated template value(s) as a data attribute. If your field input is shorter than the pattern (or input.maxLength...), it can use them as a suffix for validation purposes. YES -this will not be practical for regexes with complex case outcomes; but for fixed-position template pattern matching -which is USUALLY what is needed- it's fine (if you happen to need something more complex, you can build on the methods shown in my code...)
The example is for a bitcoin address [ Do I have your attention now? -OK, not the people who don't believe in digital currency tech... ] The key JS function that gets this done is validatePattern. The input element in the HTML markup would be specified like this:
<input id="forward_address"
name="forward_address"
type="text"
maxlength="90"
pattern="^(bc(0([ac-hj-np-z02-9]{39}|[ac-hj-np-z02-9]{59})|1[ac-hj-np-z02-9]{8,87})|[13][a-km-zA-HJ-NP-Z1-9]{25,34})$"
data-entry-templates="['bc099999999999999999999999999999999999999999999999999999999999','bc1999999999999999999999999999999999999999999999999999999999999999999999999999999999999999','19999999999999999999999999999999999']"
onkeydown="return validatePattern(event)"
onpaste="return validatePattern(event)"
required
/>
[Credit goes to this post: "RegEx to match Bitcoin addresses?
" Note to old-school bitcoin zealots who will decry the use of a zero in the regex here -it's just an example for accomplishing PRELIMINARY validation; the server accepting the address passed off by the browser can do an RPC call after a form post, to validate it much more rigorously. Adjust your regex to suit.]
The exact choice of characters in the data-entry-template was a bit arbitrary; but they had to be ones such that if the input being typed or pasted by the user is still incomplete in length, it will use them as an optimistic stand-in and the input so far will still be considered valid. In the example there, for the last of the data-entry-templates ('19999999999999999999999999999999999'), that was a "1" followed by 39 nines (seeing as how the regex spec "{25,39}" dictates that a maximum of 39 digits in the second character span/group...) Because there were two forms to expect -the "bc" prefix and the older "1"/"3" prefix- I furnished a few stand-in templates for the validator to try (if it passes just one of them, it validates...) In each template case, I furnished the longest possible pattern, so as to insure the most permissive possibility in terms of length.
If you were generating this markup on a dynamic web content server, an example with template variables (a la django...) would be:
<input id="forward_address"
name="forward_address"
type="text"
maxlength="{{MAX_BTC_ADDRESS_LENGTH}}"
pattern="{{BTC_ADDRESS_REGEX}}" {# base58... #}
data-entry-templates="{{BTC_ADDRESS_TEMPLATES}}" {# base58... #}
onkeydown="return validatePattern(event)"
onpaste="return validatePattern(event)"
required
/>
[Keep in mind: I went to the deeper end of the pool here. You could just as well use this for simpler patterns of validation.]
And if you prefer to not use event attributes, but to transparently hook the function to the element's events at document load -knock yourself out.
You will note that we need to specify validatePattern on three events:
The keydown, to intercept delete and backspace keys.
The paste (the clipboard is pasted into the field's value, and if it works, it accepts it as valid; if not, the paste does not transpire...)
Of course, I also took into account when text is partially selected in the field, dictating that a key entry or pasted text will replace the selected text.
And here's a link to the [dependency-free] code that does the magic:
https://gitlab.com/osfda/validatepattern.js
(If it happens to generate interest, I'll integrate constructive and practical suggestions and give it a better readme...)
PS: The incremental-regex package posted above by Lucas Trzesniewski:
Appears not to have been updated? (I saw signs that it was undergoing modification??)
Is not browserified (tried doing that to it, to kick the tires on it -it was a module mess; welcome anyone else here to post a browserified version for testing. If it works, I'll integrate it with my input validation hooks and offer it as an alternative solution...) If you succeed in getting it browserfied, maybe sharing the exact steps that were needed would also edify everyone on this post. I tried using the esm package to fix version incompatibilities faced by browserify, but it was no go...
I strongly suspect (although I'm not 100% sure) that general case of this problem has no solution the same way as famous Turing's "Haltin problem" (see Undecidable problem). And even if there is a solution, it most probably will be not what users actually want and thus depending on your strictness will result in a bad-to-horrible UX.
Example:
Assume "target RegEx" is [a,b]*c[a,b]* also assume that you produced a reasonable at first glance "test RegEx" [a,b]*c?[a,b]* (obviously two c in the string is invalid, yeah?) and assume that the current user input is aabcbb but there is a typo because what the user actually wanted is aacbbb. There are many possible ways to fix this typo:
remove c and add it before first b - will work OK
remove first b and add after c - will work OK
add c before first b and then remove the old one - Oops, we prohibit this input as invalid and the user will go crazy because no normal human can understand such a logic.
Note also that your hitEnd will have the same problem here unless you prohibit user to enter characters in the middle of the input box that will be another way to make a horrible UI.
In the real life there would be many much more complicated examples that any of your smart heuristics will not be able to account for properly and thus will upset users.
So what to do? I think the only thing you can do and still get reasonable UX is the simplest thing you can do i.e. just analyze your "target RegEx" for set of allowed characters and make your "test RegEx" [set of allowed chars]*. And yes, if the "target RegEx" contains . wildcart, you will not be able to do any reasonable filtering at all.

regex value check not working

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

How do I exclude a given set of numbers from a RegEx?

I have this piece of code:
$('.numeric-year').keyup(function () {
$(this).toggleClass('field-error', /10|11|12/.test(this.value));
});
What I'd like to do is exclude a given set of numbers(e.g 10, 11, 12) from triggering the .toggleClass() function.
This question is solely to do with RegEx as the rest of the code is working. Sorry I'm terrible at RegEx stuff...learning slowly.
Any help would greatly be appreciated, Thanks
This particular case would probably be better served using a conditional based on $(this).value.
Regular expressions are a pattern matching service. If you want to check whether $x follows a specific pattern, use regexp. In your case, though, you're trying to check whether the value of a given string is equal to one of a couple values. While this could be accomplished using regexp (as bliof said, check for the presence of 1[0-2], and if true, don't run), that's a bad habit to get into... that is the job for a string comparison tool, not regex. It be possible, but it's going to be more kludgy, and in other situations this type of thinking may lead to a lot of problems and head-scratching. I would just use
$(this).value() != 10 || $(this).value() != 11 || $(this).value() != 12
Based on your reply, I would still not recommend regex, but the .inArray() construct, which is more appropriate for your situation.
After having a stab at it myself I came up with this solution
$(this).toggleClass('field-error', !/10|11|12/.test(this.value));
based on Justin Poliey's answer( Regular Expression to exclude set of Keywords ) telling me NOT to negate in the RegEx but in my code.
Hence the ! before the regex /10|11|12/ and it worked a charm. Thanks for your effort guys...Much Appreciated
You can try using positive or negative lookahead.
Lets say that you have 3 input fields:
<input type="text" value="2020" />
<input type="text" value="2010" />
<input type="text" value="2000" />
And you want to get the elements with different value than 2010 and 2000, you can do something like this:
$("input").filter(function() {
if(!this.value.match("(?=2010|2000)")) {
return this;
}
});

Jquery Plugin: ba-replacetext, Javascript working but needing help.. RegExp?

I am trying to remove text from a dropdown menu using a Jquery plugin called ba-replacetext. It's ALMOST working, but could use a bit of tweeking. Please help me out as I am still learning Jquery / JS programming. Thanks!
(trying to remove ONLY the following phrases: "less $2,800.00" and "less $200.00")
HTML Source:
<select id="ct100_mainContent_productOption_1000193123" name="optionId">
<option value="">- Select Deposit or Full Tuition -</option>
<option value="1000918521" selected="selected">Full Tuition (One Time Payment of $3,000)</option><option value="1000918519">Deposit Only ($200 Initial Payment) - less $2,800.00</option><option value="1000918520">Remaining Balance ($2,800 Following Deposit) - less $200.00</option></select>
Jquery Function:
$(function(){
$('#ct100_mainContent_productOption_1000193123').ready(function(){
$('#ct100_mainContent_productOption_1000193123 *').replaceText(/less \$(2,8|2)00\.00/gi, '');
$('#ct100_mainContent_productOption_1000193123 *').replaceText( /-+/gi, '' );
});
});
Result of this code is that only the word less is removed not the entire phrase less $2,800.00. I can't get it to work, perhaps because I am using the wrong Regexp? Thoughts? Many thanks!
If you want exactly "less $2,800.00" and "less $200.00" then you would need something along the lines of:
replaceText(/less \$(2,8|2)00\.00/gi, '')
Here the (2,80|2) will match either of the two variants above, but nothing else. If instead you want to match any for of money statement you would need:
replaceText(/less \$[0-9,.]+/gi, '')
Also, you will want to account for the "-" before your "less" since that will be dangling after replacement. Of course you will need to experiment with your exact needs for which I would recommend searching with terms "javascript regex" and find a reference that works best for you. Mine is w3schools.
u can use on all 'less' text globally ..
$('#ct100_mainContent_productOption_1000193123 option').each(function () {
var html = $(this).html();
var i = html.indexOf('less');
if (i > -1) {
$(this).html(html.substring(0, i));
}
});
Yup, your regex doesn't say anything about the dollar amount. \bless\b means "match a word boundary, then the word 'less', then another word boundary". You want something like \bless \$[0-9,.]+. You can test your regular expressions at sites like this, and it sounds like you might want to read an intro to regexes generally.
Small disclaimer: I don't know anything about ba-replacetext.

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