I want my input to be connected to functions to be validated - javascript

Good day everyone,
I want my input to validate this formula
function toCelsius(f) {
return (5/9) * (f-32);
}
So that anytime I change the input number, the answer changes. I tried this function, but I am not getting the required solution.
This is what I tried:
put=toCelsius(value);
if (isNaN(x) ) {
text = "Input is not a number";
} else {
text = toCelsius;
document.getElementById("demo1").innerHTML = put;
}

To make your code work, all you have to do is to use addEventListener and bind an event to your form. So I just made a simple form with input and a submit button, then I will listen to the button click after that I will run your provided function (with a bit modification).
So the final output will be something like this:
const input = document.querySelector("input");
const button = document.querySelector("button");
const message = document.getElementById("message");
button.addEventListener("click", toCelsius);
function toCelsius(event) {
event.preventDefault();
const inputValue = input.value;
const toCelsiusValue = (5 / 9) * (inputValue - 32)
if (isNaN(toCelsiusValue) || !inputValue) {
message.innerHTML = "Input is not a number";
} else {
message.innerHTML = ""
input.value = toCelsiusValue
}
}
<div>
<form>
<input type="text">
<button>Convert</button>
</form>
<p id="message"></p>
</div>

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Validate empty string in form

I have a form that takes the users input and concatenated that to a url (written in function). How do I check to see if the users value is empty and have an alert appear right below the form that says "Please enter a valid store URL". With out having to re write my entire function! Help!
Input form
<form id="url">
<input type="text" name="urlName">
<button onclick="return myFunction()">Try it</button>
</form>
Javscript Function
document.getElementById("url").addEventListener("submit", myFunction);
function myFunction() {
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
}
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
Check empty string I have not working
function valInput() {
if (input.value.length === 0){
alert("need valid store URL")
}
}
In myFunction you can simple add this code after creating a new instance of FormData:
if (formData.get("urlName") === "")
return alert('asdsa')
It will stop the whole function because of return and will alert you that you haven't put anything in the input box.
Actually, the whole code is kinda wrong
Here's the correct version of javascript code:
document.getElementById("url").addEventListener("submit", (event) => {
event.preventDefault()
let myForm = document.getElementById("url");
let formData = new FormData(myForm);
if (formData.get("urlName").length === 0)
return alert('Provide valid url')
EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
newUrl = redirectLink(EndOfUrl);
window.location.href = newUrl;
return false;
});
function sanitizeDomainInput(input) {
input = input || 'unknown.com'
if (input.startsWith('http://')) {
input = input.substr(7)
}
if (input.startsWith('https://')) {
input = input.substr(8)
}
var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
return regexp.test(input) ? input : 'unknown.com';
}
function redirectLink(domain) {
return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
You call the myFunction twice and you don't even prevenDefault from sending form, so the form is sent whatever you do in the myFunction.
And in HTML you don't need button. You can add input:submit which will trigger function onclick automatically. Here's the correct html code:
<form id="url">
<input type="text" name="urlName">
<input type="submit">
</form>
You can add an onBlur handler to the input.
function validate(val) {
if(val.trim() === "") {
alert("Field is required");
}
}
<input type="text" name="urlName" onblur="validate(this.value)">

How to compare two variable values?

I am making a password app where you first create a password and save it to a variable. Once the variable has the value, you can enter the password. If the user got it wrong three times, I want to hide the input box and show a message. So far it is working, but it doesn't compare the two variables. Here is my code:
<p id='password'></p>
<input type='password' title='enter your password'>
<input type="submit" onclick='passwords__()'>
<button onclick='savePassword()'>
Save Your New Password
</button>
<script>
var times = 0;
var input = document.getElementsByTagName('input')[0];
var passwords = document.getElementsByTagName('input')[0].value;
var buttons = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
function passwords__() {
times++;
if (times === 3) {
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
if (input.value === passwords) {
alert('You\'re loged in');
}
}
</script>
<script>
function firstCall() {
buttons.style.display = 'none';
}
firstCall();
</script>
<script>
function savePassword() {
buttons.style.display = 'block';
buttons2.style.display = 'none';
}
</script>
When you set var passwords = document.getElementsByTagName('input')[0].value you set password to the value when the page is loaded and not when the save password button is loaded.
You should
put the savePassword function in the same block where you defined the passwords variable
set the value of passwords in the savePassword method.
Your line
var passwords = document.getElementsByTagName('input')[0].value;
is probably running before the button is pressed, so the value isn't being retrieved when the button is pressed - move this line into your passwords__() function.
Also, use
window.onload = function() {
}
to ensure that the document.getElementsByTagName() is running after the function is fully loaded;
window.onload = function() {
var times = 0;
var input = document.getElementsByTagName('input')[0];
var buttons = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
}
function passwords__() {
times++;
let passwords = document.getElementsByTagName('input')[0].value;
if (times === 3) {
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
if (input.value === passwords) {
alert('You\'re logged in');
}
}
Side note: You have a typo in alert('You're loged in'); (loged -> logged)
what you were missing
you were comparing the second input to an empty string because you are running it before the event of clicking
there are some things you can improve here .
password disappears after save
times count to 0 when logged in
var times = 0;
var input = document.getElementsByTagName('input')[0];
var pass1;
var button = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
function passwords__(){
times++;
pass2 = input.value;
if(times === 3 && pass2 !== pass1){
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
console.log(pass1)
if(pass2 == pass1){
alert('You\'re loged in');
times = 0 ;
}
}
function firstCall(){
button.style.display = 'none';
}
firstCall();
function savePassword(){
pass1 = input.value;
input.value = '';
button.style.display = 'block';
buttons2.style.display = 'none';
}
<p id='password'>
</p>
<input type='password' title='enter your password'>
<input type="submit" onclick='passwords__()'>
<button onclick='savePassword()'>
Save Your New Password
</button>

Javascript form validation only working once

Script: NewsletterScript.js
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
if (FirstName(fname)) {
}
if (LastName(lname)) {
}
if (Country(country)) {
}
if (Email(email)) {
}
return false;
}
/*first name input validation*/
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
/*last name input validation*/
function LastName(lname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( lname =="" || lname.match(letters)) {
text="";
message[1].innerHTML = text;
return true;
}
else {
text="Last name should contain only letters";
message[1].innerHTML = text;
return false;
}
}
I'm trying to get this validation to loop until the criteria is fulfilled, currently this is only working once and if the button is clicked again it submits regardless. Button below.
Due to the script being so long its not letting me upload all of it, however its just got other validation such as phone number etc, Any help will be appreciated, cheers!
If what you want is that formValidation() returns true only when the four validation functions return true you sould write that instead of putting empty if statements :
return FirstName(fname) && LastName(lname) && Country(country) && Email(email);
This manner formValidation() will return false if one of them return false
You should consider using form onsubmit instead on the onclick on the submit button.
Instead of:
<input class="button" type="submit" value="Submit" name="submit" onClick="formValidation()" />
consider using the form submit and do not forget the return keyword:
<form onsubmit="return formValidation();" > /* ... */ </form>
Related Question: HTML form action and onsubmit issues

Preventing form submit based on entering the same numbers in the box input

I have an input box here
<input type="text" size="9" maxlength="9" id="my_account" name="my_account" value="" >
and here I am disallowing users to enter the same numbers in the box, but what I really want is to prevent the form submit instead
var inputNode = document.getElementById('my_account');
inputNode.addEventListener('keydown', (event) => {
var inputValue = event.key;
var inputNodeValue = inputNode.value;
var length = inputNodeValue.length;
if (length === 3 && inputNodeValue[0] === inputValue) {
event.preventDefault();
}
});
this is my form prevent default
$("form#customer-summary").submit(function(e){
e.preventDefault();
alert("prevent submit");
});
How can I combine these two parts so I dont allow users to submit same numbers in the box ?
var inputNode = document.getElementById('my_account');
var customer_summary = document.getElementById('customer-summary');
customer_summary.addEventListener('submit',function(e){
if(!is_unique(inputNode.value)){
e.preventDefault();
alert("prevent submit");
}
});
function is_unique(val){
for(var i=0;i<val.length;i++){
if(val.indexOf(val.charAt(i)) != val.lastIndexOf(val.charAt(i))){
return false;
}
}
return true;
}
I think this should do the trick. Working jsfiddle: https://jsfiddle.net/m31h1zhg/2/.

Categories

Resources