Javascript RegExp should check four-digit input for plausibility - javascript

I want to program a JavaScript code which checks the input into an input field if it is a double two-digit HEX value. The input must contain exactly 4 digits and letters between a to f and/or 0 to 9. The following code leads to an error with a four digit input.
function check() {
var input = (document.getElementById("textField").value);
if (input.length == 4 && input.match([A-Fa-f0-9])) { alert("the input matches the requirements");}
else {alert("input is invalid");}
}
<input type="text" id="textField">
<button type="button" onclick="check()">check!</button>

If you are using regex you can define the length and simplify your test. You need to put your regex string in '/ /'.
if (input.match('/[A-Fa-f0-9]{4}/')) { ... }

Related

Auto Format text after entry in vuejs

I am trying to auto-format the postal code after entry by the user. The postal code rule is Please use the format A0A 0A0 or 12345. So if the user enters L9V0C7, it auto reformats to L9V 0C7 and when the postal code includes all digits like 12345, it stays as it is. The maxlength should be 6 when the postal code has numbers and alphabets and 5 when the postal code includes only numbers. Help me fix this handlePostalCode method.
The issue I am facing is when I enter L9V0, 0 disappears and I am not able to enter the postal code any further.
<v-text-field
label='Postal Code'
class="required"
v-model='postal_code'
required
#input="handlePostalCode"
validate-on-blur
:rules='postalCodeRules'>
</v-text-field>
postalCodeRules: [
value => /^[A-z]\d[A-z] \d[A-z]\d$|^\d\d\d\d\d$/.test(value) || 'Please use the format A0A 0A0 or 12345'
]
handlePostalCode() {
if (this.postal_code.match(/^[0-9]+$/) != null) {
var replacedInput = this.postal_code.replace(/\D/g, '').match(/(\d{0,3})(\d{0,2})/);
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + '' + replacedInput[2];
}
else {
var replacedInput = this.postal_code.match(/(\w{0,3})(\w{0,3})/);
console.log(replacedInput)
this.postal_code = !replacedInput[2] ? replacedInput[1] : replacedInput[1] + ' ' + replacedInput[2];
}
}
The problem is that when the space has been entered after the first three A0A characters, that the regular expression (\w{0,3})(\w{0,3}) cannot cross that space, and will match the empty string with the second capture group, losing out on anything else that follows.
I would suggest the following:
Make the distinction between the first and second postal code rule based on the first character only: if it is a digit, apply the first rule, if not, apply the second rule
The logic you have for the all-numbers case is overly complex: after having removed the non-digit characters, all that is left to do is to clip the string to at most 5 characters. You can use slice for that.
The logic for the second rule could first remove all non-alphanumeric characters (so also spaces would be removed)
Then it could remove any digit that follows immediately after a previous digit, and remove any letter that follows immediately after a previous letter
Finally it could clip the string to 6 characters, and inject the space if there are 4 or more characters.
Here is how your function would look:
function _handlePostalCode() {
this.postal_code = /^\d/.test(this.postal_code)
? this.postal_code.replace(/[^\d]/g, "")
.slice(0, 5)
: this.postal_code.replace(/\W/g, "")
.replace(/(\d)(?:\d+)|([A-Z])(?:[A-Z]+)/gi, "$1$2")
.slice(0, 6)
.replace(/^(...)(.)/, "$1 $2");
}

How can I count the number of digits of a number with leading zeros in javascript?

I am taking a field value, that should be a 4 digit number.
I want to make sure that the value is a 4 digit number and if not, have a pop up that says "enter a 4 digit number".
I noticed that when I put the field value into a variable it does not take any of the leading zeros. The last test case I ran the code with was a value of '0000'.
var relay = this.getField("RELAY NUM").value;
var relayString = relay.toString();
var relaySplit = relayString.split("");
console.println("relay= " + relay);
console.println("string= " + relayString);
console.println("split= " + relaySplit);
for(i = 0; i < 4; i++){
if (relaySplit[i] >= 0) {
console.println("Looks good so far");
} else {
console.println("Please enter 4 digit number");
}
}
--------------------------------------------------------
relay= 0
string= 0
split= 0
Looks good so far
Please enter 4 digit number
Please enter 4 digit number
Please enter 4 digit number
true
Instead of traversing arrays, an approach you may want to consider is using a regex to determine whether the input value meets your criteria. Then on events such as keyup (using jQuery here but not necessary), you run the validation and apply styles, or send forth the popups as you wish. I put a limit on the length of the input so users are not able to enter MORE then expected input, but this isn't necessarily needed.
$("#input").keyup(function() {
let input = $("#input").val()
let isValid = validate(input)
$("#val").text(isValid ? "Valid" : "Invalid")
})
function validate(val) {
let x = /^[0-9]{4}$/
return x.test(val)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="input" maxLength="4" />
<label id="val"></label>
</div>

Allow digits to be replaced in a length-limited field

I am using a Regex to validate a number field. This allows only numbers in the field and the max length is 3 characters. Whenever there are 1 or 2 characters in the field and I select them by double clicking on them I am able to change the number by just pressing any other number.
However when the value contains 3 numbers, which is the max length of the field, when I select the number and try to input other number it doesn't work; I cannot input anything.
I thought this is an issue with the regex, but it's not. The issue is max length.
i tried changing max length whenever it hits the max length and I try to change it it doesn't work.
// Restricting negative numbers and special characters from qyt field and maximum digits to 3
$('.js-bundle-qty').on('keypress', function(event) {
if (event.keyCode != 8) {
console.log('demo');
var regex = new RegExp("^[0-9]{0,3}$");
var inputValue = String.fromCharCode(!event.keyCode ? event.which : event.keyCode);
var key = $(this).val();
key = key + inputValue;
if (!regex.test(key)) {
console.log('enter');
event.preventDefault();
return false;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999">
https://jsfiddle.net/sanket4real/310sgheL/30/
To have the field show only integers and then allow the next pressed integer to force the oldest character from the value, or be replaced by selecting them you can use a regex to replace non-digit characters and slice() within an input event handler, like this:
$('.js-bundle-qty').on('input', function() {
$(this).val((i, v) => v.replace(/[^0-9]/g, '').slice(-3));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="js-bundle-qty" max="999" length="3" />

How do I format my input field using replace regex with javascript and jQuery?

I want to format my <input id="phone_number" type="tel" name="phone_number" maxlength="14"> to have a value like this (123) 456-7890
My current jQuery code:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
var phoneNumberVal = jQuery("#phone_number").val();
var phoneNumberUsFormat = phoneNumberVal.replace(/(\d{3})(\d{3})(\d{2})/,"($1) $2-$3");
jQuery("#phone_number").val(phoneNumberUsFormat);
}
});
The code above can format a phone number like this: (123) 456-7890 only after typing all the numbers.
What I want to happen is start adding a parentheses and a dash when the user reaches the 3rd and 6th digit
What I currently tried is this:
jQuery("#phone_number").on("keypress", function(event) {
var phoneReg = /[0-9]/g;
var phoneKey = String.fromCharCode(event.keyCode);
if(!phoneReg.test(phoneKey)){
// dont display characters
return false;
} else {
// display numbers only
if(phoneNumberVal.length < 4) {
newNumber = phoneNumberVal.replace(/(\d{3})/,"($1) ");
jQuery("#phone_number").val(newNumber);
}
}
});
The problem with the updated code above is not being able to detect the 6th digit then automatically add a -
Any help is greatly appreciated. Thanks
I suggest you to follow that process:
If the current input's value is not corresponding to the (XXX) XXX-XXXX format, checks the number of digits only.
If more or exactly 6 (= XXXXXX...), converts to (XXX) XXX- plus the rest if present.
Else if bewteen 3 and 6 (= XXX...), converts to (XXX) plus the rest if present (note the last space in the format I wrote).
Then updates the input's value.
Else if the displayed format is right, just avoid the possibility to type more characters.
The code snippet below (with some bonuses):
$('#telephone').on('keyup', function(e) {
// If not removing a character...
// (Without that check, you'll not be able to remove characters correctly.)
if (e.key !== 'Backspace') {
let value = $(this).val();
// If the value is not corresponding to wanted format...
if (!/\(\d{3}\) \d{3}-\d{4}/.test(value)) {
// Only keeps digits.
value = value.replace(/[^\d]/g, '');
// If we have at least 6 digits, converts the value to "(XXX) XXX-...".
if (value.length >= 6) {
value = `(${value.substring(0, 3)}) ${value.substring(3, 6)}-${value.substring(6)}`;
}
// If we have at least 3 digits (but less than 6), converts the value to "(XXX) ...".
else if (value.length >= 3) {
value = `(${value.substring(0, 3)}) ${value.substring(3)}`;
}
// Updates the input's value.
$(this).val(value);
}
// If the format is correct, just avoid to have too much characters.
else {
$(this).val(value.substring(0, 14));
}
}
});
// Doesn't display unwanted characters.
// (Did this on a different event. Try replacing "input" by "keyup" to see why.)
$('#telephone').on('input', function() {$(this).val($(this).val().replace(/[^\d() -]/g, ''));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="telephone">
Try something like this after the 6th character?
$("input[name='phone']").keyup(function() {
$(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input name="phone" maxlength="14" />

A convenient way to accept a fixed length number with decimal points

Basically I need to accept a simple decimal value string from a input box.
The length of the input is fixed to 5 digits so it is allowed to accept only 5 digit value.
But if the length of integer part is 5, it should be able to accommodate at least 2 more decimal points or should at least accommodate 2 decimal digits (excluding the decimal separator ) at any time.But the length of the integer part should not exceed 5 digits.
I thought used the following way :
//co2-weight is the class of input field
//by default the max-length and size is 6
$( '.co2-weight' ).keyup(function() {
if($(this).val().indexOf('.')>1)
{
$('.co2-weight').attr('size','9');
$('.co2-weight').attr('maxlength','9');
}
else
{
$('.co2-weight').attr('size','6');
$('.co2-weight').attr('maxlength','6');
}
});
But again here it need to check the length of integer part again and set it to 5.
Is there any shorter or convenient way ?
UPDATE:
The basic problem was to dynamically adjust the length in proper cases which are missing in the answers.
You could use this code, which will not allow:
more than 5 integer digits, nor
more than 2 decimal digits, nor
more than one decimal point, nor
any other character than digits or decimal point
It also applies the attribute changes dependent on whether there is a decimal point.
It responds to the input event, as there are ways of changing the contents without the keyup event firing (e.g. through context menu, mouse,or other device).
$( '.co2-weight' ).on('input', function() {
var good = $(this).val()
// remove bad characters and multiple points
.replace(/[^\d.]|\.(?=.*\.)/, '')
// remove any excess of 5 integer digits
.replace(/^(\d{5})\d+/, '$1')
// remove any excess of 2 decimal digits
.replace(/(\.\d\d).+/, '$1');
if (good !== $(this).val()) {
// Only if something had to be fixed, update
$(this).val(good);
}
var pointPos = good.indexOf('.');
// Determine max size depending on presence of point
var size = good.indexOf('.')>1 ? 8 : 6;
// Use prop instead of attr
$('.co2-weight').prop('size',size);
$('.co2-weight').prop('maxlength',size);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <input class="co2-weight" size="6" maxlength="6">
This is the perfect case where you use regular expressions.
In your case this is the regular expression pattern that you need ^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$
In javascript you would use it this way:
$(this).val().match(/^([0-9]{0,5}(\.[0-9]{0,2}){0,1})$/)
This line alone returns null if it does not find your match. An array of the matches if it does find a match.
If you need to test out this regular expression use https://regex101.com/
Using RegExp you can validate the format of the input like the following example ...
// regular expression to allow 12345.12
var regExp = new RegExp(/^\d{1,5}\.?\d{0,2}$/);
// initialize form elements
$('.valid').hide();
$('.invalid').hide();
$('.submit').prop('disabled', true);
$('.co2-weight').keyup(function() {
// on keyup validate against regular expression
if (regExp.test($(this).val())) {
$('.valid').show();
$('.invalid').hide();
$('.submit').prop('disabled', false);
} else {
$('.valid').hide();
$('.invalid').show();
$('.submit').prop('disabled', true);
}
});
$('.form').submit(function() {
// alert to show input was valid
alert('submitted');
});
.valid {
color: green;
}
.invalid {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type something in the input to see if submit button become enable</p>
<form class="form">
<input type="text" class="co2-weight">
<input type="submit" class="submit">
</form>
<p class="valid">Input format is valid</p>
<p class="invalid">Input format must be <= 99999.99</p>

Categories

Resources