Currently I am adding Javascript validation to a ASP.NET textbox. The requirement is the first two characters should take alphabetic (a-z) and last characters should be numeric (0-9). Maxlength is 4. This should in done in keypress event.
As I am newbie to JS, don't have much idea on how to do this.
Here is a quick way of adding a client side JavaScript validator to a textbox.
Please note that this works on LostFocus, instead of the Keydown, but you can change it to keydown if you really think thats the way to go.
Check the Fiddle: http://jsfiddle.net/B4xwK/
Also, this requires jQuery to be loaded on the client side.
$('#myInput').blur(function(e) {
var r = new RegExp("[A-Za-z]{2}[0-9]{2}");
var valid = r.test(e.target.value);
});
Related
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
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" />
I want to create a Input Box for entering the private entering details of a person, On which first character has to be A or E and rest can be alphanumeric and no special character are allowed. I need to do validation for the same that no one enter any special character and First character has to be A or E (all has to be check on the client side)
Can any one guide me how to proceed
Look in to regex with JavaScript, along with the keydown event. You can attach a function to the keydown event, and inside this function check the input box(es) match and then proceed as you wish.
Something like this: (not tested)
<script>
function checkInput() {
var inputToCheck = document.getElementById('my_input');
if (!inputToCheck.value.match(/[AE]\w+/)) {
// do something here, like alert them or remove special characters with .replace
}
}
</script>
<input id="my_input" onkeydown="checkInput();" />
If this is the only field to validate I would write my own with js & regexp as Leonard Challis wrote (but on the keyup event).
If there will be a lot of fields and perhaps multiple forms on the site, I would consider a framework. This is pretty good: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
If you would be using that one you could write a custom function for your special needs. http://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage
This sounds like a homework assignment (since starting with specifically “E” or “A” sounds very artificial), so I’d suggest first deciding on the interpretation of the task. Should “E” and “A” be interpreted case-insensitively? What exactly does “alphanumeric” mean? For example, is “Σ” or “Я” or “١” alphanumeric? If the purpose is to do the checks client-side, should you try to make the page completely non-functional when JavaScript is disabled, or should you just do the checks client-side as far as possible? (In the latter case, consider using the pattern attribute in HTML. On some modern browsers, it causes the check to be performed even when JavaScript is disabled.)
I want to allow only numbers(1 to 5), a $(dollar) .(decimal) and '(singlequote) in a textbox. I want to do this on keyup event. If user types anything other than these character, it should be replaced with a *. Please tell how can I do it?
You can strip the string on key-up like this:
$('input[type=text]').keyup(function(){
$(this).val($(this).val().replace(/[^1-5$.']/g, '*'));
});
Keep in mind that you should verify this on the server side (there are a plethora of ways around it on the client side).
Consider the following text box:
<input type="text" name="quantity" id="quantity_field" />
Using jQuery I want to restrict the set of valid inputs into quantity_field by the following regexp:
<script>
var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>
More specifically I want to make the browser discard any characters entered into quantity_field that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)
Examples:
If the user types "foo 234" only "234" would get entered in the text box.
If the user types "001230" only "1230" would get entered in the text box.
If the user types "foo1bar" only "1" would get entered in the text box.
Question: What is the simplest way to acheive this using jQuery?
Not an answer to your question (since I have no knowledge of jQuery), but the regex ^[1-9]*[0-9]*$ might not do as you expect or think. It matches empty strings but also a number like 000000. I expect that you don't want that since your first character class [1-9] explicitly ignores the zero. I think you should change the first * into a +: ^[1-9]+[0-9]*$. However, that regex will reject the (single) number 0. If you want to include that, you should do: ^(0|[1-9]+[0-9]*)$.
If you don't know how many characters the user is going to type in (and just want to restrict them to numbers), the jQuery Validation Plugin is your best bet.
$('form.to-validate').validate({
rules: {
quantity: { digits: true }
}
});
That will only allow the user to enter in digits. If you know how many characters the person is going to type, then I also recommend using the Masked Input plugin for jQuery, which will give the user a nice visual indication of what they need to type and also prevent them from entering in characters you do not want in the field.
If you're not after just digits and must check against a regular expression, this post has the method to add a custom validation method to the jQuery Validation Plugin which should get you what you want.
Hope that helps!
I advise you to let the user tpye whatever he wants, then do a validation on submit of the form. (Of course you must still check on the server-side as he could easily disable or alter the javascript validation code)
For validation look into the
jQuery Validation Pluging
Define a global variable "oldVal" (not described below), which contains the last known good value. Bind to the keydown action for the input field:
<script>
$("#quantity_field").keydown(function() {
var newVal = $("#quantity_field").val();
var quantityRegexp = /^(0|[1-9]+[0-9]*)$/;
// success
if (quantityRegexp.test(newVal)) {
oldVal = newVal;
// hide error
$("#quantity_field_error").hide();
}
// else failure
else {
$("#quantity_field").val(oldVal);
// display error message
$("#quantity_field_error").show();
}
});
</script>
This should get you started