I have a problem with my function in javascript, I try to replace automatically the first character when a user types any character, for example.
If the user types the letter a, in the input (with my function) replace that letter with the plus sign (+).
I want to add in my function a condition that allows to add automatically the plus sign at the beginning of the input and if is possible besides mustn't allow to delete the first character from the input.
Now my function allows to write only numbers.
<div>
<label>Write a phone number:</label>
<input type="text" maxlength="12" onkeypress="return number(event)"/>
</div>
<script type="text/javascript">
function number(e){
var tecla = e.keyCode;
if (tecla==8 || tecla==9 || tecla==13){
return true;
}
var patron =/[0-9+]/;
var tecla_final = String.fromCharCode(tecla);
return patron.test(tecla_final);
}
</script>
Updated, if you want past +44
Try to this one, and change if you need it
function phoneMask() {
num = $(this).val().replace(/\+4{1,2}|\D/g,'');
$(this).val("+44" + num);
}
$("#test").keyup(phoneMask);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Write a phone number:</label>
<input type="text" maxlength="12" id="test"/>
</div>
Related
I am trying to make sure the input field pattern should work, but all i am getting is an error that format is wrong
<input type="text" id="Phone" name="Phone" maxlength="14" value="" class="required" required="" data-msg-required="Please enter the Telephone number." pattern="/^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$/" placeholder="(XXX) XXX-XXXX">
<input type="submit">
the number is automatically formatting to (xxx) xxx-xxxx
so what is wrong here
also i am trying to remove the message it displays if the value is invalid and add the red border to the input field
var cell = document.querySelector("input[name='cellphone']");
cell.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
var ele = document.getElementById("cellphone");
$(ele).parents(".fui-form").addClass("fui-form-error");
};
})(), true);
If your goal is to just make sure that the input matches the pattern:
(XXX) XXX-XXXX, there are a couple things to take note of.
First of all, like Barmar said, when you use a regular expression in the pattern attribute of an HTML input element, that expression shouldn't be between forward slashes //.
Also, your regular expression is overly complicated. You can just do something like this:
// This javascript is just extra. Not important part.
const form = document.forms[0]
form.addEventListener('submit', e => {
e.preventDefault()
const { Phone: phone } = form.elements
// you could also do \s{1} for one space instead of a plain space if you want
console.log(phone.value, /\(\d{3}\)\s{1}\d{3}-\d{4}/.test(phone.value))
})
<form>
<input
type="text"
id="Phone"
name="Phone"
maxlength="14"
value=""
class="required"
required
data-msg-required="Please enter the Telephone number."
pattern="\(\d{3}\) \d{3}-\d{4}"
placeholder="(XXX) XXX-XXXX"
/>
<input type="submit">
</form>
Added a little extra JavaScript that will print the value of the input plus whether or not it matches the pattern. However, if you try adding any value inside the input that doesn't match the pattern, the form won't submit.
Let's go through each part of the regular expression:
I first escape these \(\), since I don't want to use them to capture a group. I want them to be part of the actual pattern
I want there to be exactly 3 numbers within those first parentheses. \d is shorthand for [0-9], and {3} means I want 3 of them.
There must be one space.
Then we require 3 numbers followed by a hyphen (-) followed by 4 numbers.
If you don't want the default error message to appear, and you want to do something else in case of an error, here's an option:
const form = document.forms[0]
const phone = form.elements.Phone
const regex = /\(\d{3}\) \d{3}-\d{4}/
form.addEventListener('submit', e => {
e.preventDefault()
console.log(phone.value, regex.test(phone.value))
})
phone.addEventListener('input', e => {
if (!regex.test(e.target.value)) {
if (!phone.classList.contains('error'))
phone.classList.add('error')
} else {
phone.classList.remove('error')
}
})
input[type='text'] {
outline: none;
border: none;
box-shadow: 0 0 1px rgb(0 0 0 / 15%);
}
input:not(:focus).error {
border: 2px solid red;
}
<form>
<input
type="text"
id="Phone"
name="Phone"
maxlength="14"
value=""
class="required"
required
data-msg-required="Please enter the Telephone number."
placeholder="(XXX) XXX-XXXX"
/>
<input type="submit">
</form>
I'm adding an event listener to the input which checks whether or not the user's input is valid after each new character typed. If the user leaves the input box (not focused), and the value of the input doesn't match our pattern, the input has a red border. If you're prefer some other behavior, you can just play with this code a little.
Is it possible to validate a phone number, but the same should not be required if left empty?
If the input is empty - the form should submit
If a phone number is entered, then its required that it be 10 digits.
If it doesn't match the 10 digits pattern - than the form should not submit
Please advise, thank you
If you use the required attribute you're game over. So don't.
its required that it be 10 digits
Use the ^\d{10}$ pattern:
input[type=text]:invalid{
border: 1px solid red;
}
<form>
<input type="text" pattern="^\d{10}$" />
<button>SUBMIT</button>
</form>
The form doesn't submits if
There's some value AND the value does not matches the regex in pattern.
The form submits if
There's no value
There's value AND has exactly 10 digits
You can use regex to match most phone numbers or an empty string.
var pat = /^$|^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
console.log(pat.test(''))
console.log(pat.test('8169428451'))
console.log(pat.test('(816)842-8455'))
console.log(pat.test('asdfs'))
function check(){
var pat = /^$|^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
var phone = document.getElementById('phone')
if(pat.test(phone.value))
{
document.getElementById("myForm").submit();
}
else
{
return false
}
}
<form id="myForm">
<input id="phone" type="text" />
<button onclick="check(); return false;">Go</button>
</form>
I have 4 input fields next to eachother.
I'm trying to force the user to enter 1 character per input field and as soon as they entered 1 character, they need to enter the next character into the next field until the inputs finish.
However my current code is al over the place and I can't figure out what I need to do to achieve this.
This is my code:
https://jsfiddle.net/ej9tvosj/
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==0){
$(this).next('.inps').focus();
}
});
if you enter something in the first one, it will jump into the next field but it will get messed up there after.
Could someone please advice on this issue?
You need to try on input listener to detect change in input instead of keyup since you need to ensure that a character is entered before changing focus.
$(document).on('input', '.inps', function (event) {
// check for hyphen
var myLength = $(this).val().trim().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
You can compare the myLength value with 1 like in the code snippet below:
$('.inps').keydown(function (event) {
// check for hyphen
var myLength = $(this).val().length;
if(myLength ==1){
$(this).next('.inps').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
<input type="text" class="inps" >
I am trying to figure out if there is a javascript function that can validate users numeric input and output its type in a . Would match function work? Or is there a function that can validate a users input and out put if it is a phone number, social security numeric or zip code? I researched it and could not find a exactly what I need for this, found validation to ensure user is inputting numbers or letters but not process to verify its type depending on its length or special characters in it. I do not have much experience, I hope my question makes sense.
<h1>Reg Test</h1>
</header>
<br>
<p><b>Enter numeric value:</b></p>
<input id="inp" type="text">
<br>
<br>
<button type="button" onclick="pros()">Process</button>
<br>
<p id="iop"></p>
<br>
<script>
function pros() {
var numt = document.getElementById("inp").value;
}
</script>
$(".isInteger").keypress(function(){
return event.charCode >= 48 && event.charCode <= 57;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="isInteger" type="text" />
I'm trying to create an input element that:
Holds a number (string or actual number doesn't matter).
You shall not be able to enter anything else but numbers and a dot(.).
You are allowed to enter two decimals.
If no decimals are entered, two decimals (i.e. .00) shall be added to the number when leaving the input element (on-blur).
I'm working with AngularJS (1.2) and watch $valid and $invalid on the containing form.
The input is valid when the value is a number with two decimals and the value is larger than 0.
I have tried to use:
<input ng-model="price" type="number" ng-blur="addDecimals()"/>
$scope.addDecimals = function(){
$scope.price = $scope.price.toFixed(2);
}
But then I can't add zeroes as decimals (.00). As toFixed() returns a string, the value is not allowed in the input and it becomes empty.
I have also tried to use
<input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" />
$scope.changed = function(){
// removes all charachters but numbers and one dot (.);
// examples:
// if value is '1a.t9' it will be changed to '1.9'
// if value is 'qwe' it will be changed to ''
// if value is 4 it will not be changed.
$scope.price = removeAllCharsButNumbersAndDot($scope.price);
}
$scope.addDecimals = function(){
if(parseFloat($scope.price) > 0)
$scope.price = $scope.price.toFixed(2);
else
$scope.price = "";
}
With this solution [form].$valid will be set to true if the value '0' is entered. [form].$valid will be set to false only when the user leaves the input element (on-blur) which is kind of ugly.
I have tried to use ng-pattern="/^\s*(?=.[1-9])\d(?:.\d{1,2})?\s*$/", but then ng-change will not fire.
You can use https://github.com/angular-ui/ui-validate. Ui-validate is great for this. Example:
<input type="number" ng-model="priceModel" ui-validate=" 'checkPriceModel($value)' ">
//Controller:
$scope.checkPriceModel = function(value){
return value <= 0;
}
<form name="theForm" id="theForm">
<input ng-change="changed()" id="priceId" type="number" min="1" name="priceName" ng-model="priceModel" required />
</form>
is the easiest (without extra modules)
If i am getting it right, you can try following
<form name="appTest">
<div
ng-class="{ 'has-error': appTest.app.$touched && appTest.app.$invalid }">
<input type="text" ng-model="vm.text" name="app" ng-pattern={define your pattern}>
</select>
</div>
If its invalid, 'has-error' class will get applied.
You don't need ng-change for this. You can just rewrite your html like this.
<form name="theForm" id="theForm">
<input id="priceId" type="number"
name="priceName" ng-model="priceModel" required min="0" />
<span class="error" ng-show="theForm.priceName.$error.number">
Not valid number!
</span>
</form>
You can read more about it here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D