Add number before input box text after validation using JavaScript - javascript

I have this HTML form
more on top ...
<div class="form-group row">
<label for="phone" class="col-sm-3 col-form-label">Phone</label>
<div class="col-sm-9">
<input type="text" name="phone" id="phone" class="form-control" >
</div>
</div>
more on bottom ...
Here I am putting the number e.g 1671133639 and if its validate then I am adding 880 before this number. But it's adding before the input field, not input text. I mean final result should be: 8801671133639
JS Code I am using:
if (phone.value == "") {
alert("Phone number is required");
phone.focus();
return false;
} else if (!phoneRegex.test(phone.value)) {
alert("Phone number must contain only numerical value.");
phone.focus();
return false;
} else if ( phone.length > 13 ) {
alert("Invalid phone number is given.");
phone.focus();
return false;
} else {
var text = document.createTextNode('+88');
var child = document.getElementById('phone');
child.parentNode.insertBefore(text, child);
}

Don't use insertBefore, assign the new string to the input's value attribute.
const text = '+88';
const child = document.getElementById('phone');
const value = child.value;
phone.value = text + value;
document.querySelector('button').addEventListener('click', function() {
const text = "+88";
const phoneInput = document.getElementById('phone');
const value = phoneInput.value;
phoneInput.value = text + value;
})
<input type="text" value="1671133639" type="string" id="phone">
<button>Append Phone Code</button>

Related

trying to clear value in textbox in javascript function

i am trying to put validation on a textbox onkeyup. Textbox should contain only 5 digit value and after decimal only upto 4 decimal places. eg,12345 ,12345.2345
if user enter value other than regex then the texbox should become blank and i want it to be done in function and this function should be generic so that any other can use this function
.Aspx
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this.value)" />
Script function
<script type="text/javascript">
function isFloatNumber(value) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
value = "";
return false;
}
return true;
}
</script>
function isFloatNumber(elem) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(elem.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
elem.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN1' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN2' value='' runat="server" onkeyup="isFloatNumber(this)" />
You can use above snippet which will work for n numbers of inputs.
Updating value = ""; doesn't update the UI element. You should access the UI Element object by passing this and update the value like this.value = " " else you should use the selectors like document.getElementbyId() to access those object like document.getElementbyId('inpSurfIndN').value = ""
One of way you can use below logic,
function isFloatNumber(obj) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(obj.value);
if (regmatch == null || regmatch == false) {
alert("Please fil correct expression");
obj.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
var n = document.getElementById("numPeople"),
r = document.getElementById("result");
n.addEventListener("keyup", function(e) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(n.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
n.value='';
return false;
}
}, false);
<input id="numPeople" type="number" min="0" value="" placeholder="Pick a number" />
You cannot access the value variable which is passed as a parameter, it doesnt reference to the value of the input box
Instead you can access the element and change the value like below:
function isFloatNumber(eve) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
var elem = eve.currentTarget;
elem.value = "";
return false;
}
return true;
}

validating using onblur and onsubmit

I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

How can I check if the input is empty in JavaScript? [duplicate]

This question already has answers here:
How do I check for an empty/undefined/null string in JavaScript?
(52 answers)
Closed 7 years ago.
I am trying to make a factorial calculator. How can I check if the input is empty or not? I tried 'null'. But it didn't work or I couldn't use it properly.
sorry for the stupid question. I am newbie in JavaScript
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if( !(isNaN(input))) {
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else if (input == null){
return "Please input a number"
}
else{
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function() {
if (input.trim() == '') {
return "Please input a number"
} else if (!(isNaN(input))) {
var result = 1;
for (var i = 1; i <= input; i++) {
result = result * i
}
return result;
}
}
document.getElementById("input2").value = ever();
}
<p>Input:
<input type="text" id="input1" />
</p>
<p>Input:
<input type="text" id="input2" />
</p>
<button onclick="myFriday()">Calculate</button>
<p>RESULT: <span id="result" style="color:red"></span>
</p>
is that what you looking for?
function myFriday() {
var input = document.getElementById("input1").value;
var ever = function () {
if(input.match(/\D/) == null){ // changes made here
var result = 1;
for(var i = 1; i <= input; i++ ) {
result = result * i
}
return result;
}
else{ // one else is enough
return "Please input a number"
}
}
document.getElementById("input2").value = ever();
}
<p>Input: <input type="text" id = "input1" /></p>
<p>Input: <input type="text" id = "input2" /></p>
<button onclick = "myFriday()">Calculate</button>
<p >RESULT: <span id = "result" style = "color:red"></span> </p>
When you use .value you get a string value in return.
This means that when you enter nothing in the input it'll return ""
So you should change this piece of code
input == null
Into this
input === ""
Note that I also wrote === instead of ==
Using === in javascript is faster than == when the objects are of the same type.

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Fancy sliding form with more validation

I am using this fancy sliding box and having some problem with validation.It has default validation for checking where a field is empty or not but i want to add some more validation like two specific fields are equal or not or the length of a specific field is within the desired length or not.I have edited the code but facing a problem that is when a previous navigation field has any error it is also adding error class for the next navigation though it was filled correctly.
Here is my code(Be noted i don't know jquery well) :
function validateStep(step) {
if(step == fieldsetCount) return;
var error = 1;
var hasError = false;
$('#formElem').children(':nthchild('+parseInt(step)+')')
.find(':input:not(button)')
.each(function() {
var $this = $(this);
var valueLength = jQuery.trim($this.val()).length;
//i don't know how to generate a specific field value using this keyword
var pas=$('#myPassword').val().length;
var pas1=$('#myPassword').val();
var pas2=$('#VerifyPassword').val();
var pin1=$('#mPin').val();
var pin2=$('#vVPin').val();
var pas_ok=1;
if(pas1 != pas2 || pin1 ! =pin2 || pas < 5 ) {
pas_ok=0;
}
if(valueLength == '' || pas_ok==0) {
hasError = true;
$this.css('background-color','#FFEDEF');
} else {
$this.css('background-color','#FFFFFF');
}
});
var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
$link.parent().find('.error,.checked').remove();
var valclass = 'checked';
if(hasError) {
error = -1;
valclass = 'error';
}
$('<span class="'+valclass+'"></span>').insertAfter($link);
return error;
}
Here is my form:
<div id="steps">
<form id="formElem" name="formElem" action="" method="post" >
<fieldset class="step">
<legend>Account</legend>
<p>
<label for="password">Password</label>
<input type="password" name="myPassword" id="myPassword" value="<?=$myPassword;?>" AUTOCOMPLETE=OFF />
</p>
<p>
<label for="password"> Verify Password</label>
<input type="password" name="VerifyPassword" id="VerifyPassword" value="<?=$VerifyPassword;?>" />
</p>
<p>
<label for="password"> Your Personal Pin </label>
<input type="pin" name="mPin" id="mPin" value="<?=$mPin;?>" />
</p>
<p>
<label for="password"> Verify Personal Pin </label>
<input type="pin" name="vVPin" id="vVPin" value="<?=$vVPin;?>" />
</p>
</fieldset>
</form>
</div>
What you are doing is checking all input fields for every each cycle again completeley. .each() gives you one input at a time. What you want to do is differentiate them via the input's respective id and then run the checks. The following code checks the length of all 4 input fields and marks them red if their length is zero and in case of the two verify input fields it also checks whether they are the same as their original input fields. The code is untested but you should get the idea.
$('#formElem').children(':nthchild('+parseInt(step)+')')
.find(':input:not(button)')
.each(function() {
var $this = $(this);
var value = $this.val();
var valueLength = jQuery.trim(value).length;
var pas_ok = 1;
var id = $this.attr("id");
if (id === 'VerifyPassword') {
var password = $('#myPassword').val();
var vPassword = value;
if (password !== vPassword)
pas_ok = 0;
} else if (id === 'vVPin') {
var pin = $('#mPin').val()
var vPin = value;
if (pin !== vPin || pin.length < 5)
pas_ok = 0;
}
if(valueLength === 0 || pas_ok === 0) {
hasError = true;
$this.css('background-color','#FFEDEF');
} else {
$this.css('background-color','#FFFFFF');
}
});
On a side note: Always use === instead of == if you compare something in javascript.

Categories