Decimal number validate is not working with length - javascript

I'm trying to validate the decimal number pattern with specific length but no luck.
I tried this pattern="[0-9]){1,2}(\.){1}([0-9]){2}" but this works only 12.12
I'm looking for (13digits).(6digits) pattern validation and length validation.
Expected is,
`1234567891123.123456` //true
`1234567891123123456` //false since only number
`12345678911234.123456` //false since 14digits.6digits
`1234567891123.1234567` //false since 13digits.7digits
What be the better regx to fulfill the above validations?

A useful site for regex testing is https://regexr.com/
\b\d{13}\.\d{6}\b

The regex that you need should be like this:
([0-9]){13}(\.){1}([0-9]){6}
So for example in HTML form input, it would look like this:
<form action="">
<input type="text" required pattern="([0-9]){13}(\.){1}([0-9]){6}" />
<button type='submit'>Submit</button>
</form>

You can try using this:
\d{13}[.]\d{6}

Working Demo :
var regex = /^[0-9]{13}\.[0-9]{6}$/i;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
<input type="text" id="myinput"/>
<button id="testBtn" onclick=test()>test</button>

Related

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format. This should occure .on("input") meaning as the user types it should secure the right input format.
A wrong char should be replaced with a blank.
Format Example: 1.000 1.281 21212.000 21212.810Nothing like this:1.02.12 or 1919,201,00 Only a dot between the two Number blocks.
This is what i have so far:
Regex 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
Regex 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
Regex 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.
Here is the FIDDLE
Should Work in IE11
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
try this one,
^[0-9]*(\.|,)?[0-9]*$
this take below cases:
1111,
.0000
123,12
12.12
12345
but if you want only
111,11
11.11
12345
so please use this
^[0-9]+(\.|,)?[0-9]+$
to force use dot/comma please use this
^[0-9]+(\.|,)[0-9]+$
add this code
$("#testId").keyup(function(){
var vals = $("#testId").val();
if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
$("#testId").val(vals);
else
vals = vals.replace(/.$/,"");
$("#testId").val(vals);
});
and change input type to
type="text"

Javascript strip after X characters prior to form submit

UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).

Why this javascript and html code is not calculating the result?

This is the code:
<html>
<body>
<script>
function myFunction(var1,var2){
number=var1+var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo></p
</body>
</html>
When I insert 10 for number 1 and 20 for number 2, the output is:
1020
But i want it to display 30.
What can i do?
**I have tried myFunction(10,20), the result is 30.
simply use parse the variable value to integer using parseInt() method or add "+"before to your variable name. Because variables var1 and var2 returning string. To calculate those variable values, you need to convert it as a integer.
using parseInt() method
number=parseInt(var1)+parseInt(var2)
use + before variable name to convert into integer,
number= +var1 + +var2
try this code,
<html>
<body>
<script>
function myFunction(var1,var2){
number = parseInt(var1) + parseInt(var2)
//another way number= +var1+ +var2
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
using parseInt() DEMO
using + before variable name DEMO
modify your function with parseInt like:
<script>
function myFunction(var1,var2){
number=parseInt(var1)+parseInt(var2);
document.write(number);
}
</script>
You were getting output like 1020 because by default data from the textbox is taken as text type, so we need to convert it to Number Type first, for that we are using parseInt(for explicit conversion)
Your javascript thinks you are appending strings... To make sure your javascript knows it's numbers your working with you need to convert it to that type.
<html>
<body>
<script>
function myFunction(var1, var2){
number = parseInt(var1, 10) + parseInt(var2, 10)
document.write(number)
}
</script>
<form>
Number 1 : <input type="text" name="no1"><br>
Number 2 : <input type="text" name="no2"><br>
<input type="button" onclick="myFunction(this.form.no1.value,this.form.no2.value)" value="submit">
</form>
<p id="demo"></p>
</body>
</html>
For more info about parseInt check this documentation.
Update your method to
function myFunction(var1,var2){
number=parseInt(var1) + parseInt(var2)
document.write(number)
}
As this.form.no1.value is returning a string, so both the numbers are concatenated as strings instead of summing up as numbers.
Two options:
Change your input tag to
<input type="button" onclick="myFunction(parseInt(this.form.no1.value, 10),parseInt(this.form.no2.value, 10))" value="submit">
OR
Change your JavaScript function to
function myFunction(var1,var2){
var number=parseInt(var1, 10)+parseInt(var2, 10);
document.write(number);
}
It is because the values you extract from your input fields are strings. When you add two strings, they are usually concatenated. Try looking at the javascript method parseIntas Evan suggests in the comments or look at parseFloatif you want to allow floats.
parseFloat docs
Your method would then look like this:
function myFunction(var1,var2){
number = parseFloat(var1) + parseFloat(var2)
document.write(number)
}
It's now just string concatenation. Please use "parseInt()" to get the result.
thanks.
Your not doing a calculation, you are appending two Strings. In order to calculate the mathematical answer for var1 + var2 you should parse them to Integers.
result = parseInt(var1) + parseInt(var2);

Validating phone number with JavaScript

I have a form with three elements. I want to validate the phone number when the user enters it. If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox.
I have written some code but am completely stumped. The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. My code looks like this:
<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
}
</script>
<form>
<strong>FULLNAME: </strong><input type="text" / id="name"><br />
<strong>PHONE NR: </strong><input type="text" id="phone" onblur="validateForm()" />
<strong>NATIONALITY</strong><input type="text" id="nat" /><br />
<input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>
Thank you in advance for all your answers and help.
Change
document.forms[0].elements[1]
to
document.forms[0].elements[1].value
You were testing the element itself, not the element's value.
jsFiddle example
BTW, if someone enters a phone number with a dash or parenthesis (e.g. (555) 123-4567) what do you expect to happen?
Here you will find many exemple to achieve your goal :
for example if you can use only number :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You should do it with a regular expression. See here:
A comprehensive regex for phone number validation
Validate phone number with JavaScript

Comparing similar strings in jquery

How do I compare similar strings in jquery?
<script src="../../js/jq.js"></script>
<script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1==str2){
console.log('yep');
}
});
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
Comparing "One String" and "One String1" is not going to work if I'm only checking if the two values are equal. Is there any way to do this in jquery? For example I only want to compare 90% of the string.
You can see if one is contained inside the other for example:
if (str1.indexOf(str2) >= 0 || str2.indexOf(str1) >= 0)
console.log('yep');
}
Check this out : http://jsfiddle.net/Sj5dE/ You can comment out a,b block to see the similitude of the strings. It's of course case-sensitive. I hope this helps. Since your example talked about comparing two similar strings, I thought it'd be most likely that the beginning of the strings are the same so I didn't introduce any substring logic but feel free to change the function.
Try this it might work
<script src="../../js/jq.js"></script> <script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1===str2){ console.log('yep'); } });
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
In javascript you can use the substring to get the 90% of the string you would like to compare.
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase().substring(0, 10);
var str2 = $.trim($('#str2').val().toUpperCase().substring(0, 10);
if(str1==str2){
console.log('yep');
}
look on
http://code.google.com/p/google-diff-match-patch/
the demo in
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
You can check if the string is present or not by
$(".className").replace(/(^|\s)yourTextHere\S+/g, " ");

Categories