restrict characters in form field - javascript

I've an HTML field in a form and, using JS and Regex, I must restrict the characters the user can insert in the field. The user of the form can only insert the following characters ( ) * + ^ / X x, and numbers and spaces (when he digits or pastes a different character nothing is written). Is this possible? I need the Regex, I eventually know how to do with JS.

Try this regex
[^\(\)\*+\^/Xx0-9 ]
Here we are trying to find a pattern which contains none of the allowed characters. If you find it this means that the character entered was wrong.

There is no right or wrong answer to this.
Usually it is less expensive to check using the bias of the logic for the particular condition.
If it sounds better saying whats allowed, then use the allowed (positive) character class.
Allowed class: [()*+^/Xx0-9 ], Checks: <space> (-+ /-9 X \^ x
Not allowed class: [^()*+^/Xx0-9 ], Checks: \0-\37 !-' , \- . :-W Y-\] _-w y-\377
Statistically, if %99 of the data enterred were valid, the 'Allowed' class would do less work in that
not every character or range has to be checked.
Where the 'Not-Allowed' class will have to check every range.
In this particular case, the negative class has many more ranges and characters to check, its borderline
more efficient if most of the data were invalid,

With regard to:
[^\(\)\*+\^/Xx0-9 ]
None of those characters need to be escaped inside a set (but it is okay to do so).
If you want to restrict as the user types (this uses jquery methods):
$('#in1').keyup(function (evt) {
var content = $('#in1').val();
$('#in1').val(content.replace(/[^()*+^/Xx0-9]/g, ""));
return true;
});
Where 'in1' is the id of the input.

Related

Matching varying length in JS Regex

Let me explain my query with an example:
Am capturing page name from a web site. Due to design, the page name can be of varying length:
It can be
Data1|Data2|Data3
Data1|Data2|Data3|Data4
Data1|Data2
I need to write a Regex which comes true on all the above scenarios. I have something below shared by a previous user:
/(.*?)\|(.*?)\|(.*?)\|(.*)/gm;
The above works well when the string is always of four group, and there is a blank in between. But if I just have two values the regex fails. Can any user please guide?
Not sure what you meant there but does this help? But it will only accept alphanumeric values and a space
/([a-zA-Z 0-9]{1,}\|){1,}[a-zA-Z 0-9]{1,}/g
This will expect at less two Data field, and at most 4 fields
/(?:([^|]*)\|){1,3}([^|]*)/gm;
If you also want only one field (no pipe):
/(?:([^|]*)\|){,3}([^|]*)/gm;
{n,m} means allowed to repeat n trhough m times
Notice how I used [^|]* instead of .*?, so I match anything but the pipe |, also I used non matching groups (?:) so the groups that includes the pipes are invisible, i.e. you can get the fields as get them before

Jquery allow spaces in alpha numeric validation

I am trying to do a validation on a textbox value with jquery to make sure textbox accepts only alpha numeric values. I am also trying to allow spaces between words. I am not trying to allow spaces to left and right of the sentence in textbox. how can I allow spaces in middle of words in the textbox?
My trails fiddle
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
}
});
You're not going to be able to do it gracefully using only keyup, because while still in the process of typing the sentence, the space you just typed (intending it to be in the middle) is at the end.
Instead, I would do something like this:
$('#dsTest').keyup(function() {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
$('#dsTest').focusout(function() {
this.value = this.value.trim();
});
Allow spaces to be typed while typing is in progress, and strip the leading and trailing spaces with String.trim() at some reasonable later point. In my example, I use .focusout(), but you could also just trim when consuming the value.
This is an example of a broader category of validation problems in which testing WHILE input is being entered prevents the user from entering a value that would have been legal once they were done - because entering the value one character at a time requires the value to temporarily have an invalid state. There are two main ways of handling that problem:
Don't test for validation until the user has finished inputting the value
Flag invalid values rather than altering them
You can also combine the two - for instance, highlighting the field while the user is typing to show that the current value is invalid, and then also fixing the value to make it valid if they leave the field while the invalid value is still present.
In pure regex this should work /^[a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+$/g. Note that this would requires at least 2 characters in the value. If you want to also allow it to be blank then you could do /^([a-zA-Z0-9]+[a-zA-Z0-9\s]*[a-zA-Z0-9]+|)$/.
With all that said, it is prob better usability-wise to just trim the value, as mentioned by other answers, since that does not stop the user from moving forward if they accidentally add a leading or trailing space.

Javascript Simple check for webform to make sure it contains both numbers and letters (instead of my code)

I have this code:
if(address.length<=0)
{
msg.setAttribute("style", "color:red");
msg.innerHTML='Please enter address';
return false;
}
I would like to change so it checks whether the webform contains BOTH numbers and letters. Can you help me?
Thank you so much,
Jones
p.s.: So I want to make sure they also enter street name AND house number as well (example: 24 Sunshine street would be good, but if they forget house number, they would get the message).
That doesn't look like PHP at all. More like JavaScript...
Here's one way to do it in JavaScript:
var re = /^\d+\s+\D+$/;
if (re.test(address)) {
//We get here if the address is correctly formated
}
else {
//We get here if the string is badly formated
}
The regex works like this:
\d+ matches to one or more numbers
\s+ matches to one or more spaces
\D+ matches to one or more letters
If you want to accept both "24 Sunshine" and "Sunshine 24" you could instead use this:
/^(\d+\s+\D+)|(\D+\s+\d+)$/
And if we want to be extra safe and protect from the case that the user might enter an extra trailing or leading space we could either trail the string or use this ReGex:
/^\s*(\d+\s+\D+)|(\D+\s+\d+)\s*$/
Apart from regular expression which is a very nice and clear solution you can use these php functions:
first the ctype_alnum () in order to check if your string contains letters and digits and then
this on ctype_alpha() in case the above is true to check if user forgot to enter number.
In case you are interested there is also this one ctype_digit() for checking if user missed the address but gave the number.
Or if you want just a regex this it will do the job:
^[a-zA-Z]([a-zA-Z-]+\s)+\d{1,4}

Javascript RegEx partial match

I have a regular expression pattern, which validates for a three digit number
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("123.") // false
I want to use this regex as an input restriction on a textbox.
Basically, if the new value matches, i allow the character to by typed, otherwise i prevent it.
The problem is that no value will ever match, becase "1" is not a full match, and will not allow me to type it.
Is it any way of testing a partial match for a regEx in javascript?
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("12") // "partial match"
/^\d{3}$/.test("a12") // false
EDIT
\d{3} was just an example.
I need to use an email regex or a phone regex as input restriction.
"email" // true
"email#" // true
"email##" // false
"#yahoo.com" // false
EDIT 2
I have a textBox plugin with input restriction based on a regular expression.
The regular expression can be anything, a hex color Regex, for example: (#){1}([a-fA-F0-9]){6}
I need to prevent user to insert characters which doesn't match the regex.
For example, if the textbox is empty, the first allowed character would be "#".
But if i test "#" character against the regex, it will return "false", because "#" by itself is not valid.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // false
But at the same time, "#" is partial valid because it respects the regex format (and i should allow user to type it)
What i need to know is if i can verify if a string is a partial match of a regex, so i can allow the user to type the character.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#0") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#00") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#0000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#00000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000D") // is not a match, prevent typing
You could partially validate the email address by using ()? for more letters and/or characters. Every ()? going deeper in the validation tree.
The following regular expression pattern validates email address letter by letter.
^[a-zA-Z]+(#{1}[a-zA-Z]*(\.{1}[a-zA-Z]*)?)?$
It does not take into account every possibility out there, but for basic ones like aa#bb.dd it works just fine and there's room to improve it further.
You would be better off by using a library like maskedinput.js.
You can then setup your text input like follows:
jQuery(function($){
$("#your_input").mask("999");
});
UPDATE
you can use a validator for forms and preset specific types of fields to validate
You can specify a range in the expression so that it matches anything between one and three digits like so:
/^\d{1,3}$/.test("1") // true
/^\d{1,3}$/.test("12") // true
/^\d{1,3}$/.test("123a") // false
Just provide a regex that allows for partial matches. e.g. /^\d{1,3}$/
According to your last edit, this should work:
/^#[a-fA-F0-9]{0,6}$/
You'll want to use explicit "|" partial matches. For your color matching example it's pretty simple, you just need to explicitly match an empty string partial
/^(|#[a-f0-9]{0,6})$/i.test(inputStr)
For an email it's more complicated since there are more partial match combinations
/^(|\w+|\w+#|\w+#\w+|\w+#\w+\.|\w+#\w+\.\w+)$/.test(inputStr)
Note that you can't get away with something like /^(|\w*#|...)$/ since that matches #blah.com which isn't a valid partial input.

How to ensure only valid numeric characters are entered into a textbox?

Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?
Such as
.00 or 0.00, but not 0.00.00 or 0a
What I'd like to do is catch any invalid characters before they appear in the textbox.
If it's not possible with jQuery, what's the best way to approach this?
I know with JavaScript I can test isNaN() and then return false, but that's going to start getting hairy when I have to account for all possible keystrokes.
just use a regex match
$('#formelement').val().match(/[-+]?[0-9]*\.?[0-9]+/)
(excluding selector, everything else is plain javascript)
As noted in comments, since you need to do it for each character inserted you have to consider an empty decimal part valid (eg. /[-+]?[0-9]*\.?[0-9]*/)
Since people in comments forces me to be precise I can suggest you how to work out how to use this matching for your purpose (but so you don't let anything to the OP imagination :( )
You can split the regex in 3 regexs, one for the first part (eventual sign and whole part), one for the first part plus the dot symbol and one for the whole number.
You validation routine should accept the input while it's being written if it matches at least one of the threes regex just described and the validation done at the end should accept just when the last regex is matched (since you are submitting the value and you need it to be correct)
It's a little tricky, since you want to make sure you can enter all numbers left to right, but something like this:
$("input").keyup(function() {
this.value = this.value.match(/[-+]?[0-9]*\.?[0-9]*/);
});
Try it out with this jsFiddle
Note how I'm checking the number from left to right. This means that + must be valid. Also 5. must be valid, or you could never enter 5.0 or +5.
Now the above has some major issue (try the arrow keys).
Here's a slightly more elegant solution that accommodates a default value as well:
$(function() { // <== DOC ready
var prev=""; // Initial value to replace default text with
$("input").click(function () { // Include a select on click
$(this).select(); // if you have a default value
});
$("input").keyup(function() {
if(/^[-+]?[0-9]*\.?[0-9]*$/.test(this.value)) // If number....
prev = this.value; // store it as the fallback
else
this.value = prev; // else go to fallback
});
});
Try it out with this jsFiddle
Example HTML for the above:
<input type="text" value="Enter only a number" />
Note how when you use .test() you have to test from the beginning ^ to the end $.
Seems like a work for regular expressions:
var x = '0.00';
var y = '0.000.00';
x.match(/^[0-9]+\.*[0-9]*$/);
y.match(/^[0-9]+\.*[0-9]*$/); // evaluates to null
You can use a plugin or another separate library to do form validation. An example:
http://www.geektantra.com/2009/09/jquery-live-form-validation/
Regular expressions would also work if you wanted to handle this manually.
I'm using this plugin for my projects:
http://www.texotela.co.uk/code/jquery/numeric/
it's simple but have some bugs with negative values,
anyway it works great for a simple use!
you can you use it like so:
$("input.numericInput").numeric();

Categories