I'm currently working on a project in which I need to fetch street/city details from a DB using a zipcode. Dutch zipcodes use a "1111 AA" format, I would like to have this entered in a single input field while forcing the first four characters to be numeric and the last two to be alphabetical.
I've been googling this quite a bit, have found ways to force either one, but none to combine it into a single input field and I don't seem to be crafty enough to combine them myself.
Thank you.
We use this in alot of sites, especially for phone #s
http://digitalbush.com/projects/masked-input-plugin/
To handle the specific pattern you entered, try something like this in the javascript function that validates form input:
var pattern = new RexExp( '[0-9]{4} [A-Z]{2}' );
if( inputFieldValue.search( pattern ) == -1 )
{
// throw error condition.
}
else
{
// The pattern matched. Continue on.
}
This is finally a question where regular expressions are a suitable solution.
Try this:
var zip = "1111 AA"
var regex = new RegExp("^[0-9]{4}\\s?[A-Z]{2}$");
regex.test(zip);
Note that this will not allow lowercase characters, and will allow the zipcode without whitespace (like this: 1111AA). Try some googling to find out how to allow or disallow those.
You can use the new html5 pattern attribute for that:
<form>
<input name="zipcode" type="text" pattern="\d{4}\s?[A-Z]{2}" length="7" />
<input type="submit" />
</form>
If the attribute isn't supported, you fall back to a javascript solution, checking the input field with a regex before submit like the following:
var pattern = /[0-9]{4}\s?[A-Z]{2}/;
string.match(pattern);
Take a look at the demo fiddle.
Related
I'm having a problem with my regex validation code. I'm trying to figure out how can I validate a vehicle license plate number. The code that I wrote is listed below this message. This is written down in React inline code and I've written down two different regex expressions and both of the come out to be false. The license plate number should be in this format XX-NNNN-XX.
X = Letter
N = Number
const [licencePlate, setLicencePlate] = useState('');
var ValidateLicencePlate = /^[A-Z][A-Z]-[0-9][0-9][0-9][0-9]-[A-Z][A-Z]$/g ;
var regex = /^[A-Z]{2}-[0-9]{4}-[A-Z]{2}$/g ;
<input name="licence-plate" type="text" className="feedback-input" maxLength='10' onChange={(e) => setLicencePlate(e.target.value.toUpperCase())} placeholder="XX-NNNN-XX"/>
This regex can solve the problem.
let regex = /^[A-Z]{2}-\d{4}-[A-Z]{2}/gi
This regex will match two alphabet at the beginning, four digits at the middle and two alphabet at the end.
You can use regex as following
<input pattern="/^[A-Z]{2}-\d{4}-[A-Z]{2}/g"/>
You can put your regex in the pattern attribute of the input element. I do not see you are using regexps yo have defined anywhere in your listing.
<input pattern={regex}/>
If you have a regex constraint to validate against it may be better and more comfortable to use Constraint Validation API.
<input pattern="your regex here"/>
Browser already validates everything in form elements if you constraint them with various ways like patter attribute and unless you tell it not to validate. But still I see many code bases trying to do the validation themselves. It is unnecessary since there is a way platform itself supports and does itself.
I am new to javascript and I couldn't find the exact code for my need.
I want a text field with maxlength="5" which should look like ex:AE456, LM975. i.e., the first two letters ahould be alphabets and next three letters should be numbers.
the text area should accept input according to this pattern only. I don't want any alert. Simply it has to accept whatever typed only in this pattern.
Javascript is preferrable. Any help is greatly appreciable.
Thanks in advance.
HTML5 supports pattern where a field can accept values as per the supplied regex. You can find related post here.
Regex Patterns for HTML5 Text Field
But if you want to support older browser, then you have to attach events like "keypress" to the input field, and handle the event to validate the input
If you have this HTML:
<input type="text" id="text1" />
Then you could use this Javascript:
function validateInput() {
var val = document.getElementById("text1").value;
return /[A-Z]{2}\d{3}/i.test(val);
}
and call it like:
if (validateInput()) {
// Matches pattern: #####
}
DEMO: http://jsfiddle.net/GgQsz/
This allows uppercase and lowercase alpha characters at the beginning. If you want to only allow uppercase, remove the i flag for the Regex.
What you need is a regular expression. Check out regular expression here. This should give you an idea as to how to check for your condition.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
I know that SO is not a code generator, but I break my head and I'll got mad with this RegExp.
I've <input /> type text, in a HTML <form />. The input is automatically filled when the user double-click on elements in a specific list.
This event will generate string like "[text:number]" or "[text:number:text]", and place it at the cursor position in my <input /> field.
The first goal of this process is to construct a mathematic formula structure. I mean, the generated strings between brackets will insert elements, then I want to allow the user to put only numbers and operators.
I've tried to bind the keydown event, and test the char with String.fromCharCode(e.which); but for the keys "+" or "-" (and other operators) this function returns alphabeticals chars. Without success.
Then, I've finally decided to use the keyup event, then use a RegExp to replace the <input /> value.
$("#inputID").keyup(function(){
var formule = $(this).val();
var valid_formule = formule.replace(CRAZY_REGEXP,'');
$(this).val(valid_formule);
});
So, my question is as follows :
How construct a javascript RegExp, to remove all chars which are not between brackets, and which are differents of ()+-*/,. and numbers.
An example :
"a[dse:1]a+a[dse:5]a+a[cat:5:sum]a+(a10a/5,5)!"
will become
"[dse:1]+[dse:5]-[cat:5:sum]+(10/5,5)"
I'm open to another way to achieve my goal if you have some ideas.
Thanks !
You may try something like this:
var re = /[^\]\d\(\)+\-*\/,.]+(?=[^\[\]\(\)]*(?:\[|\(|$))/g;
$("#inputID").keyup(function(){
this.value = this.value.replace(re, "");
});
Keep in mind, though, that you have to be sure that the parenthetical structure is coherent with your syntax.
Advice: use RegExr to test your regular expressions, but remember that it's more powerful than Javascript regex support.
I have this RegEx that validates input (in javascript) to make sure user didn't enter more than 1000 characters in a textbox:
^.{0,1000}$
It works ok if you enter text in one line, but once you hit Enter and add new line, it stops matching. How should I change this RegEx to fix that problem?
The problem is that . doesn't match the newline character. I suppose you could use something like this:
^[.\r\n]{0,1000}$
It should work (as long as you're not using m), but do you really need a regular expression here? Why not just use the .length property?
Obligatory jwz quote:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Edit: You could use a CustomValidator to check the length instead of using Regex. MSDN has an example available here.
What you wish is this:
/^[\s\S]{0,1000}$/
The reason is that . won't match newlines.
A better way however is to not use regular expressions and just use <text area element>.value.length
If you just want to verify the length of the input wouldn't it be easier to just verify the length of the string?
if (input.length > 1000)
// fail validation
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();