Validation of a mathematical formula based on user input - javascript

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.

Related

Text Replacement With RegEx

I am using Sublime Text to write some Javascript and need to do a simple text replacement in the editor in order to set code up. I can do it manually but I figured there must be a way to have the replacement occur automatically with RegEx. I've used RegEx a bunch before but have never used it to grab data from one part of the code to reference and edit another part of the code. For example, I have this:
var example_1 = 836;
var example_2 = 837;
var example_3 = 838;
var example_4 = 846;
And then I have this:
SELECT_122=836
SELECT_143=837
SELECT_144=838
SELECT_145=846
I want these to use the corresponding values and format them like this:
SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4
Note that I'm updating the equal signs to colons with spaces so I figured doing all these changes could be done with some sort of search and replace. I have a large amount of these so I figured it would be best to learn how to do this if it's possible.
I don't have SublimeText, but you said in a comment that you want to do it through a text editor. Here is what works for me in EditPad Pro, it may work in Sublime.
Search:
(?s)(var (example_\d++) = (\d++).*?SELECT_\d++)=\3
Replace:
\1: \2,
Then I click "Replace". This will replace the first instance (SELECT_122=836) with "SELECT_122: example_1,"
Then I click "Replace Next" multiple times, and the SELECT_ strings are left looking like this:
SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4,
Is this what you want?
Hope the regex and replacement string at least get you started. :)

how to get only two letters as alphabets and remaining as numbers in text area field

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

Force different characters at different positions

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.

Trying to remove trailing text

I having the following code. I want to extract the last text (hello64) from it.
<span class="qnNum" id="qn">4</span><span>.</span> hello64 ?*
I used the code below but it removes all the integers
questionText = questionText.replace(/<span\b.*?>/ig, "");
questionText=questionText.replace(/<\/span>/ig, "");
questionText = questionText.replace(/\d+/g,"");
questionText = questionText.replace("*","");
questionText = questionText.replace(". ",""); i want to remove the first integer, and need to keep the rest of the integers
It's the third line .replace(/\d+/g,"") which is replacing the integers. If you want to keep the integers, then don't replace \d+, because that matches one or more digits.
You could achieve most of that all on one line, by the way - there's no need to have multiple replaces there:
var questionText = questionText.replace(/((<span\b.*?>)|(<\/span>)|(\d+))/ig, "");
That would do the same as the first three lines of your code. (of course, you'd need to drop the |(\d+) as per the first part of the answer if you didn't want to get rid of the digits.
[EDIT]
Re your comment that you want to replace the first integer but not the subsequent ones:
The regex string to do this would depend very heavily on what the possible input looks like. The problem is that you've given us a bit of random HTML code; we don't know from that whether you're expecting it to always be in this precise format (ie a couple of spans with contents, followed by a bit at the end to keep). I'll assume that this is the case.
In this case, a much simpler regex for the whole thing would be to replace eveything within <span....</span> with blank:
var questionText = questionText.replace(/(<span\b.*?>.*?<\/span>)/ig, "");
This will eliminate the whole of the <span> tags plus their contents, but leave anything outside of them alone.
In the case of your example this would provide the desired effect, but as I say, it's hard to know if this will work for you in all cases without knowing more about your expected input.
In general it's considered difficult to parse arbitrary HTML code with regex. Regex is a contraction of "Regular Expressions", which is a way of saying that they are good at handling strings which have 'regular' syntax. Abitrary HTML is not a 'regular' syntax due to it's unlimited possible levels of nesting. What I'm trying to say here is that if you have anything more complex than the simple HTML snippets you've supplied, then you may be better off using a HTML parser to extract your data.
This will match the complete string and put the part after the last </span> till the next word boundary \b into the capturing group 1. You just need to replace then with the group 1, i.e. $1.
searched_string = string.replace(/^.*<\/span>\s*([A-Za-z0-9]+)\b.*$/, "$1");
The captured word can consist of [A-Za-z0-9]. If you want to have anything else there just add it into that group.

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