What is the right regex to allow blank or numeric values - javascript

I want to validate one variable named "Port" in my JavaScript to accept only either numerical digits or a blank value. I am not sure exactly what regex I can use to satisfy both conditions. Can anyone suggest me logic to use under my if loop to validate this?

If you want to achieve your goal with regexes, you are looking for:
const regex = /^\d*$/;
console.log(regex.test("")); // true
console.log(regex.test("8080")); // true
console.log(regex.test("4d54")); // false

Related

How to get the valid part of a regex match

I want to test if a user string is "ok so far", in that it might not be valid as a whole but it is a subset of a valid one.
I have a regex say ^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]$
such that "1234-1234-5678-5678" is valid
"1234-12" or even "1" does not match pattern but its a valid subset of a valid format, in other words the input is ok so far.
is there a neat way of doing this without making many many regexes, its friday.
Not sure if I understood well your problem, but I think you want to have something like this:
^([0-9]{4}-){1,3}[0-9]{1,4}$
Working demo
This will match set of 4 digits and can have the last set from 1 to 4 digits
You can also shorten your regex with:
^(\d{4}-){1,3}\d{1,4}$
You could possibly use one final regex for validation of the form you currently have, and a on the fly regex for the user input being valid for each subset.
My idea would be to have ([0-9]{1,4}-)+
For your case this will check as one types:
/^(\d(\d(\d(\d(-(\d(\d(\d(\d(-(\d(\d(\d(\d(-(\d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?$/
This regex will match key for key as you type, although it is a little cumbersome.
^([0-9]{1,4}|[0-9]{4}-[0-9]{0,4}|[0-9]{4}-[0-9]{4}-[0-9]{0,4}|[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{0,4})$
Here is a live example

Javascript Input sterilization, trying to prevent a string from getting into my number field

I setup an if statement that checks for numbers, strings, and null. However when I type "1a" it passes my validation. How does javascript handle this? What type of datatype is this?
How can I say ONLY numbers no strings at all
you can use regex to check if its a numeric value
var reg = new RegExp(/^\d+$/);
reg.test(yourValue);
A simple solution would be to let the browser handle your validation by using the input type number:
<input type="number">
To validate it in JavaScript, you can use the Number() constructor and check for NaN. Note however that it does not only accept digits:
console.log(Number('1a')) // NaN
console.log(Number('1')) // 1
console.log(Number('1.2')) // 1.2
console.log(Number('1e2')) // 100
parseInt()/parseFloat() will not solve your problem, since it ignores trailing non-digits:
console.log(parseInt('a1')) // NaN
console.log(parseInt('1a')) // 1
console.log(parseInt('1')) // 1
console.log(parseFloat('a1')) // NaN
console.log(parseFloat('1a')) // 1
I assume you mean you input 1a into an input box and receive it in a JS function to check what the user has input? If so anything that comes into your function will be a string. If that is the case, you can:
1- Check for the input by doing Number("1a"), which would return NaN if it is not a number or Number("1") would return 1.
2- Use input type=number.
3- Use an input mask library to prevent user from inputing letters and only numbers. In that case you wouldn't need to check on the JS side. Something like this might be what you want: https://github.com/RobinHerbots/jquery.inputmask
As a note it is important to say that JS is not a typed language, so essentially there are no types.

regular expression to allow only integer and decimal no precision required

This is a duplicate post, The requirement is little different though, I want to know a regular expression that would allow only decimal numbers. Found a similar solution here.
regular expression to allow only integer and decimal
but the solution has a comma in it.
I dont need the comman at all in the Regex exp.
/^[0-9]+([\,\.][0-9]+)?$/g; answer found on the site
I applied my logic based on the explaination in the post.
/^[0-9]+([\.][0-9]+)?$/g; My modification
Is there any other way to handle this?
This is the right way to call:
var regex = new RegExp(/^[0-9]*([\.][0-9]+)?$/g);
console.log(regex.test('0.85')); // true
console.log(regex.test('0,85')); // false
console.log(regex.test('.35')); // true
console.log(regex.test('')); // false
console.log(regex.test('.')); // false
console.log(regex.test('4')); // true
I suggest a little modification on the regular expression, I've changed the multiplicity of the first block to zero or more so .35 will be considered valid, as you ask in the comment above.
Here is a plunker.

jquery validate digits backwards (123456 and 654321)

good morning,
i need a guide for use a function to jquery validate where user write digits backwards.
Example:
user write: 123456.
the system validate that write backwards: 654321.
i think use Jquery validate personalize function.
$.(#myform).validate({
});
thanks!!
There is no .reverse for strings, but there is one for arrays, so:
"123456".split("").reverse().join(""); // "654321"
And then simply check whether that string matches the user's input. I don't know the validation plugin but you can simply use the === operator.

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