Javascript Condition : Real time validation - javascript

Can anyone please help me fix my javascript condition.
The scenario is this.
When I input 9 digit, label should turn red. But if the field is empty and i input 10 digit, label should turn blue. Im having a hard time to fix this.
function validateField(testField)
{
var reg2 = /^([\d])/;
if(testField.value.length > 0)
{
if(reg2.test(testField) == false)
{
document.getElementById("testlabel").style.color="red"
return false;
}
else
{
document.getElementById("testlabel").style.color="black"
return true;
}
}
else
{
document.getElementById("testlabel").style.color="blue";
return true;
}
}
<label id="testlabel">Test101: </label>
<input name="txtNum" type="text" id="Num" pattern=".{10,}" minlength="10" maxlength="10" onblur="validateField(this);" >

There are multiple issues with your code
Regex - If you need to validate the Regex for having 10 digits only then you can use the Regex \d{10}. Your Regex ^([\d]) only matches a digit at the start of the string.
reg2.test(testField) should be changed to reg2.test(testField.value), you are trying to compare the TextBox value and not the textbox itself.
function validateField(testField)
{
var reg2 = /\d{10}/;
if(testField.value.length > 0)
{
if(reg2.test(testField.value) == false)
{
document.getElementById("testlabel").style.color="red"
return false;
}
else
{
document.getElementById("testlabel").style.color="blue"
return true;
}
}
else
{
document.getElementById("testlabel").style.color="black";
return true;
}
}
<label id="testlabel">Test101: </label>
<input name="txtNum" type="text" id="Num" pattern=".{10,}" minlength="10" maxlength="10" onblur="validateField(this);" >

Related

using HTML variables with JavaScript

I'm creating a sign up system and tying to make a code using JavaScript that checks the phone number the user is entering and only allows it to be used if it is 10 characters long.
this is my code so far:
JavaScript:
<script type="text/javascript">
function phoneIsValid()
{
var phoneL = document.getElementById("phone").length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
</script>
HTML:
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
the problem is that it always replys that the phone number is not 10 cahracters long, even if it is. what am I doing wrong? I dont know much Javascript and I cant find a solution on the internet.
You don't even need JS for this:
<form>
<input type="text" minlength="10" maxlength="10" required placeholder="Phone number (10 digits)" />
<button>Send</button>
</form>
function phoneIsValid()
{
var phoneL = document.getElementById("phone").value.length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
function checkPhone() {
if(phoneIsValid()) {
alert('Phone number is valid');
} else {
alert('Phone number is NOT valid');
}
}
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
<button type="button" onclick="checkPhone()">Check it</button>
As mentioned in comments - you need to validate value of the textbox, not textbox itself.
It'd be quite simple
HTML: First create a submit button, so that we can detect when the user submits it
<input type="text" id="phone" name="phone" placeholder='Enter Phone number..'/>
<button id='submit'>Submit</button>
JavaScript:
<script type="text/javascript">
document.getElementById('submit').onclick = function(){ // trigger when button is clicked
let phoneL = document.getElementById('phone').value.length; // get the length of the value
if (phoneL >= 10) { //check if the length is 10 characters or more
alert('Valid phone number!')
} else {
alert('Invalid phone number!')
}
}
</script>
If you need any other help, feel free to let me know
Try getting the length of the "value".
var phoneL = document.getElementById("phone").value.length;
˄

Querying input text with javascript and checking for a value does not work

I would like to query an input field with Javascript and from a value of over 20 a button should be released. Javascript works too. Unfortunately, if I enter the number with a comma instead of a period, it no longer works.
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
if (checkEmpty_ek.value >= 20) {
document.getElementById("neuerbuttonspeichern").disabled = false;
} else {
document.getElementById("neuerbuttonspeichern").disabled = true;
}
});
<input type="text" id="ek" name="ek" value="$ek">
<input type="button" id="neuerbuttonspeichern" value="Send" />
Try: let inputValue = Number(checkEmpty_ek.value.replace(",",".")); inside function.
And then check: (inputValue >= 20)
It is not the most elegant solution, but it will resolve if the user types the number with a comma or with letters and special characters.
Bye.
Use type = number
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
document.getElementById("neuerbuttonspeichern").disabled = checkEmpty_ek.value < 20;
});
$ek<input type="number" id="ek" name="ek" value="0">
<input type="button" id="neuerbuttonspeichern" value="Send" disabled />
if (Number(checkEmpty_ek.value.replace(/,/g, '')) >= 20) {
{
document.getElementById("neuerbuttonspeichern").disabled = false;
} else
{
document.getElementById("neuerbuttonspeichern").disabled = true;
});
If you are just looking to remove any potential commas from the input, this will do it. But like someone else commented, we aren't really familiar with your user interaction expectations. Chances are, you'll be filtering out more than commas.
Just replace the comma with the dot.
Number(checkEmpty_ek.value.replace(",","."))
Number ("20.") === 20
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
console.log(checkEmpty_ek.value)
if (Number(checkEmpty_ek.value.replace(",",".")) >= 20) {
document.getElementById("neuerbuttonspeichern").disabled = false;
} else {
document.getElementById("neuerbuttonspeichern").disabled = true;
}
});
<input type="text" id="ek" name="ek" value="">
<input type="button" id="neuerbuttonspeichern" value="Send" />

jQuery Greater than and Smaller than check

This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});

Javascript - validation, numbers only

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

Javascript phone number validation

I need to validate a phone number in javascript.
The requirements are:
they should be 10 digits, no comma, no
dashes, just the numbers, and not the
1+ in front
this is what I wrote so far
function validatePhone(field,alerttxt) {
with (field) {
if(value.length > 10) {
alert(alerttext);
return false;
}
for(i = 0; i < value.length; i++) {
if(parseInt(value[i]) == NaN) {
alert(alerttxt);
return false;
}
}
return true;
}
}
function validateForm(thisform) {
if (validatePhone(phone,"Invalid phone number")==false) {
phone.focus();
return false;
}
}
}
<form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
<ol>
<label for="phone">Your phone <span class="red"></span></label>
<input id="phone" name="phone" class="text" />
</li>
</ol>
</form>
but, obviously it doesn't work.
How can I write the validatePhone() function so that it works?
phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) {
alert("not 10 digits");
} else {
alert("yep, its 10 digits");
}
This will validate and/or correct based on your requirements, removing all non-digits.
Google's libphonenumber is very helpful for validation and formatting of phone numbers all over the world. It is easier, less cryptic, and more robust than using a RegEx, and it comes in JavaScript, Ruby, Python, C#, PHP, and Objective-C flavors.
You could use Regular Expressions:
function validatePhone(field, alerttext) {
if (field.match(/^\d{10}/)) {
return true;
}
alert(alerttext);
return false;
}
Code to except only numbers braces and dashes
function DoValidatePhone() {
var frm = document.forms['editMemberForm'];
var stripped = frm.contact.value;
var isGoodMatch = stripped.match(/^[0-9\s(-)]*$/);
if (!isGoodMatch) {
alert("The Emergency Contact number contains invalid characters." + stripped);
return false;
}
}
Fixed function:
function validateForm(thisform) {
if (validatePhone(thisform.phone,"Invalid phone number")==false) {
thisform.phone.focus();
return false;
}
return true;
}
Add the pattern in which format you want directly in input tag.
<input id="phone" name="phone" pattern="\d{10}" class="text" />

Categories

Resources