I have a form in which I have a field where the user enters their phone number and we force them to start with +34 followed by 9 digits (12 digits in total are what that field should have), but then when I change at +31 for example I pick it up as if it were +34, this is using a
<input type="text">
This is a variable
let phone2 = phone.length
This is the contidion I am using in Javascript
if (phone != '+34' & phone2 < 12) {
evt.preventDefault ();
alert ('The phone number must start with +34 and have at least 12 digits');
}
If anyone can help me
Try this:
Note that onblur means that the test function will fire when the input field loses focus. So, to run the test, type something and then click outside the input field.
const $ = document.querySelector.bind(document);
function test() {
const phone = $('input').value;
if (phone.substr(0, 3) !== '+34' || phone.length < 12) {
alert('The phone number must start with +34 and have at least 12 digits');
} else {
alert('good job');
}
}
<input onblur="test()" placeholder="Phone (must begin with +34)" />
Related
I have an input.
<input id="phoneNumber"/>
How can I validate if the inserted value from user is a valid phone number or not using jQuery ?
Thanks.
You can use oninput to check if input has some values entered or not.
When 10th value is entered you can use a alert but this will not be enough because after alert, user can still enter more values. So use maxlength="10" to allow only 10 numbers.
Also if you don't want to allow text but numbers only than you can use .replace(/[^\d]/, '') to replace any non-number . And show that it is not a number.
function validPhone(phoneNum)
// check for valid phone numbers in the format 999-999-9999
{
if (phoneNum.value.match(/[^\d]/)) {
phoneNum.value = phoneNum.value.replace(/[^\d]/, '')
document.querySelector("#demo1").innerHTML = "Sorry numbers only";
} else {
document.querySelector("#demo1").innerHTML = "";
}
var strPhone = phoneNum.value;
var rePhone = /\d{3}-\d{3}-\d{4}/;
if (strPhone.length >= 10) {
phoneNum.select();
document.querySelector("#demo1").innerHTML ="No more numbers plz, only 10 digits allowed in Phone number.";
}
document.querySelector("#demo").innerHTML = strPhone.length;
};
#demo1 {
color: red;
}
<input class="form-control" oninput="validPhone(this)" type="text" name="username" placeholder="Enter Phone number" maxlength="10" id="phoneNumberForForgotPassword" data-val-required="نام کاربری را وارد نمائید.">
<div id="demo1"></div>
<div id="demo"></div>
Password validation is not working in the login form. Here is my code:
function verifyPassword() {
var str = document.getElementById("t1").value;
if (str.match(/[a-z]/g) &&
str.match(/[A-Z]/g) &&
str.match(/[0-9]/g) &&
str.match(/[^a-zA-Z\d]/g) &&
str.length >= 8)
return true;
else
return false;
}
You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.
document.getElementById('t1').addEventListener('change', function() {
if (!verifyPassword()) {
alert("Invalid password");
}
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
if (!verifyPassword()) {
event.preventDefault();
alert("Invalid password");
}
}
Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.
The syntax ?=.*[x] means that you must have the condition x in your string.
Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.
function verifyPassword() {
var str = document.getElementById("t1").value;
var regEx = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})");
if (regEx.test(str) &&
str.length >= 8)
console.log("good")
else
console.log("bad")
}
<div class="txt_field">
<input type="password" id="t1" value="" required>
<label>Password</label>
<button onclick="verifyPassword()">Verify</button>
</div>
I want to create a script function which will validate if the user input contains more than one decimal i.e 2.434 should be the correct number but if the user tries to input a NUMBER LIKE 2.4.5.6 it will not take the input in the field. It will take only number after a decimal point but not another single decimal point. no 2.2.2. but 2.2222. Will use it in a .net page.
tried different patterns like ^-{0,1}\d+.{0,1}\d*$ but could not get result. added the function i am already using. need to add the decimal part in the given code.
function isNumberKey(evt) {
var first;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) {
return true;
}
if (charCode == 46 || charCode > 31 && (charCode < 48 ||
charCode > 57))
return false;
return true;
}
text box will take input when 2.22 or 3.455654 but won't take 2.3.34.4. when the user writes something like this the cursor won't change the position or take the input number.
The code provided does not validate the entire string. It just checks that the key pressed is a digit, which does not help much. There are many ways to do what you want:
1- Browser validation using type="number":
You can use an input with type "number"; then the browser will do a validation on its own before the form submits (this also accepts integers though):
<input type="number" name="decimal" />
2- Browser validation using the patternattribute:
A handy property you can set for inputs is the pattern attribute. You can set it to the desired regex, and the browser will make sure the user's input matches the regex before submitting the form.
<input type="text" name="decimal" pattern="^-?\d+\.?\d*$" />
3- Custom validation with Javascript:
This approach definitely gives you more flexibility, and allows you to validate once the user typed the input, instead of validating on form submit.
Assuming you have a text input, you can listen to the onchange event to validate the entire string, after the user has finished typing their input.
Edit: As for the regular expression, you need to escape the dot, so replace (. by \.). Plus, {0, 1} is equivalent to ?, as pointed out by #CodeManiac in the comments.
var input = document.getElementById("decimal-input");
input.onchange = function() {
var text = this.value;
if(!text.match(/^-?\d+\.?\d*$/)) {
this.value = ""; //clear input
console.log("Please enter a valid decimal.");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="decimal-input" placeholder="Enter a decimal..."/>
</form>
in the event target is the reference to the input element. So you are able to obtain the whole string
function isNumberKey(evt) {
s=evt.target.value;
console.log(s);
if (s.length !==0){
arr=s.split(".");
if (arr.length>0){
return false;
}
///... other checks...
}
there might be also a dirty way to check the whole number
try {
x=eval(s*1) ;
} catch (ex){
return false
}
or just do it on the enter key to implement a tiny calculator in your input ;)
Funtion setupField is called with the id of an input field to be initialized with an onkeyup event that will only allow valid input to be entered into the field. The regular expression it uses allows an optional + or - sign. The number itself can be of the format: 123, 123., 123.45, or .45
To allow an initial entry of the +, -, or . characters, the regular expression must also consider these characters to be legal input. When the form is submitted, there is always the possibility that only one of these 3 characters or no characters at all have been entered. It is easy enough to test for a valid decimal number by testing isNan(parseFloat(input)) against the input.
^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$
<!doctype html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8">
<script>
function setupField(field)
{
let re = /^(([+-]?\d+(\.\d*)?)|[+-]?(\.\d+)|[\+-\.])$/;
field.autocomplete = "off";
field.saveValue = field.value;
field.onkeyup = function() {
var v = field.value;
if (v === '' || re.test(v)) {
field.saveValue = v;
}
else {
field.value = field.saveValue;
}
};
field.onchange = function() {
var v = field.value;
if (isNaN(parseFloat(v)))
console.log('You entered invalid input.');
};
}
function init()
{
setupField(document.getElementById('x'));
}
</script>
<body onload="init();">
<input type="input" id="x" size="10">
</body>
</html>
I'm working on a page that has a text box and a button (there's more to it, but these are the things that are giving me trouble). When the button is clicked, it's supposed to verify that there are only 3 letters entered in the text box.
Here is the html creating the input box and button:
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
And here is the Javascript function to check the input:
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput < 3) {
alert("Please enter 3 letters");
}
}
To test that this works I'm trying to enter only a single letter, but when I click the button, nothing happens. Any idea what I can do to fix this?
Check the length property:
if (TTinput.length < 3)
What you are doing is to set to the TTinput variable the value of the text box. So now TTinput contains a string. What you need is to get its length, and the length of a string in javascript can be got by the lenght property:
var str = "ABCD";
str.length; // 4
http://www.w3schools.com/jsref/jsref_length_string.asp
function validate() {
var TTinput = document.getElementById("3letters").value;
var input_length = TTinput.length;
if(input_length < 3) {
alert("Please enter 3 letters");
}
}
If you want exactly 3 characters use:
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
or
if(TTinput.length != 3) {
alert("Please enter 3 letters");
}
*This (TTinput.length < 3) alone will consider 4, 7, 350,... characters valid.
For my studies I need to create a simple script that checks if the entered data (suppose to be a 5 digit zip code) actually has 5 digits. If more or less then 5 digits entered, a alert should pop up.
So far I managed to get the alert for more and less then a 5 digit entry, but even when entering 5 digits, the alert will come up as well.
Since js is not my favourite subject I am lost, even tho it seems to be a simple thing.
Thanks in advance for answers and hints.
<script type="text/javascript">
<!--
function CheckZip ()
{
var content = document.forms['zipfield'].Field.value;
var length = content.length;
if (length >=5) (alert('Please enter a 5 digit zip code!'));
else if (length <=5) (alert('Please enter a 5 digit zip code!'));
else (length ==5) (alert('Valid entry'))
}
//-->
</script>
</head>
<body>
<div align="left">
<p>Please enter a 5 digit zip code</p>
<form name="zipfield" action="post"><input name="Field" size="5">
<br />
<br />
<input name="check" value="Check entry" onclick="CheckZip()" type="submit">
</form>
How about this:
if (content.length !== 5) {
alert('Please enter a 5 digit zip code!');
} else {
alert('Valid entry');
}
Check your condition..
When length is 5 it will go to the first if statemenet because you have specified it to be
>= 5
So when length is 5 , it will never hit the statement else (length ==5)
if (length >5) {
alert('Please enter a 5 digit zip code!')
}
else if (length <5) {
alert('Please enter a 5 digit zip code!')
}
else (length ==5) {
alert('Valid entry')
};
Better
if( length === 5){
alert('Valid entry');
}
else{
alert('Please enter a 5 digit zip code!');
}
Check Fiddle
You have other syntax errors in your script
if (length >=5) (alert('Please enter a 5 digit zip code!'));
--^-- Supposed to be { --^-- supposed to be }
Also you are ending the if loop with a semicolon ; .. Need to remove that ..
Otherwise the statement in else if and else will never be executed
5 is greater than or equal to 5, so the error alert will come up.
You should be using > and <, instead of >= and <=.
>= means greater than or equal to, <= means less than or equal to. Your problem is that if your input is exactly 5 characters long then:
if (length >=5)
Will evaluate as true, and you won't get to your else statement.