how set a oninput with minlength - javascript

How can I put a input with a oninput that only works when I have a minlength defined?
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction()"><br><br>

If I understand your question correctly, you want to run some code only when your minlength="8" is satisfied.
You can check if the input is correctly validated using the validity object. It contains the state of all the validation flags. See https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
<p id="demo"></p>
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if input is tooShort
if (el.validity.tooShort) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"
} else {
// Run this code if minlength is satisfied
document.getElementById("demo").innerHTML = el.value;
}
}
</script>
You could however also just check the length of the value like this:
<p id="demo"></p>
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="myFunction(this)"><br><br>
<script>
function myFunction(el) {
// Check if value is at least 8 characters....
if (el.value.length < 8) {
// You can just leave this empty
document.getElementById("demo").innerHTML = "Too Short"
} else {
// Run this code if length is at least 8
document.getElementById("demo").innerHTML = el.value;
}
}
</script>

read attribute value using this.getAttribute method and then relatively call function
<input type="text" class="password2" id="password" name="password" minlength="8" oninput="this.getAttribute('minlength') !== undefined ? myFunction() : null">

you can try this:
html: <input type="text" minlength="3" id="input">
Javascript:
let val = document.querySelector("#input");
val.addEventListener('input', () => {
let vaLength = document.querySelector("#input").value
if(vaLength.length >= 5){
console.log("the input has more than 4 character...")
}
})

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;
˄

Javascript conditional hiding and showing

Hello guys I'm confused with javascript code, I want a program that gets the input from the user, and if that input matches a specific value like 1234 I want it to hide part of the form. E.g.
var x=document.getElementById('pin').value;
function hidden() {
if (x.value=1234){
document.getElementById('pin').style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin">
<button onclick="hidden()">Enter</button>
var x=document.getElementById('pin');
function checkPin() {
if (x.value == "1234"){
x.style.display="none";
}
}
<input type="number" name="pin" placeholder="Please Enter Your Pin" id="pin" />
<button onclick="checkPin()">Enter</button>
The value is not a native number, but a string, and you're assigning in the conditional check. Instead of '=' use '==' or '==='.
Try this:
function hidden() {
var x = document.getElementById('pin').value;
if (x === '1234'){
document.getElementById('pin').style.display = 'none';
}
}

Javascript validation nightmare

I'm trying to get my "username" and "password" fields to verify that there is information in them before submitting the form.
What should I need to add to my HTML and to my JavaScript to have them work! If you want to suggest a new JavaScript, please do!
HTML:
<form action="validateForm.html" id="registrationForm">
<label for="username" id="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" value="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" id="passwordLabel">* Password:</label>
<input type="password" name="password" id="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" id="submit" />
</form>
JavaScript
function validateForm()
{
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
if(!document.forms[0].username){
alert("Username field is required!");
}
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
}
One way would be getting your input by id and then validate its value
HTML
<input type="text" id="username" />
<input type="password" id="password" />
JS
function validateForm()
{
if(!document.getElementById("username").value) // true if input value is null, undefined or ""
{
alert("Username field is required!");
}
else if(!document.getElementById("password").value)
{
alert("Username field is required!");
}
}
(i strongly recommend you to use more attractive ways of giving users feedback than JS alerts)
I think all of those checks are incorrect in some for, let's start with the first one:
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
It's document.getElementsByName() (notice the plural)
The function returns an array of elements, so you'd still need to check for the value of the one you want (probably 0)
This is going to be true always as the field exist, you need to check the value in the input, but right now you are just checking the existence of the input.
Next one is similar:
if(!document.forms[0].username){
alert("Username field is required!");
}
You are checking the existence of the field, not its value
This type of selection is not recommended, you should be using a document.getElementBy... better.
And finally:
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
It looks like you tried to make a for loop but copy-pasted from above and got this mess... not even going to try to understand why the loop.
Recommendations:
Use the attribute id and read the fields using document.getElementById()
To check if a field has content, check its value: .value
Add an event handler for the form (onsubmit="validateForm()")
Make the form validator return false if one of the fields is incorrect (otherwise the form will be sent even with the incorrect fields)
Optionally: use the HTML5 required attribute.
So the function would look like:
function validateForm()
{
if(document.getElementById("username").value == "")
{
alert("Username field is required!");
return false;
}
// check the other fields
// .....
}
May I suggest something like this instead:
HTML:
<form action="validateForm.html" onSubmit="return validateForm(this)">
<label for="username" name="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" placeholder="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" name="passwordLabel">* Password:</label>
<input type="password" name="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" />
</form>
JS:
function isEmpty (field) {
return field.value === "";
}
function validateForm (form) {
// assume the form to be valid
var isValid = true;
// create a variable to store any errors
var errors = "";
// check if the username is empty
if(isEmpty(form.username)) {
// our assumption is incorrect, the form is invalid
isValid = false;
// append the error message to the string
errors += "Username field is required!\n";
}
if (isEmpty(form.password)) {
isValid = false;
errors += "Password field is required!\n";
}
// display the errors if the form is invalid
if (!isValid) {
alert(errors);
}
return isValid;
}
This way, you are passing the form directly to the validateForm function and can easily access each field using their name properties. You can then check if they're empty by determining what their value contains.
If you need to get the DOM by it name means it will returns an Array so you need to get it by
if(!document.getElementsByName("username")[0].value == ""){
//do ur stuff
}
or
if(!document.getElementById("username").value == ""){
//do ur stuff
}

how to check password field with confirm password field

I have written a function in javascript to chek whether both fields are same or not:
javascript code:
function validate();{
var x= getElementByName("password");
var y= getElementByName("retype_password");
if(x==y) return;
else alert("password not same");
HTML code: HOW CAN I CALL THE ABOVE WRITTEN FUNCTION IN THE HTML CODE
password : <input type= "password" name="password"> <br><br>
retype password : <input type="password" name="retype_password" > <br><br>
thanks in advance
password : <input type= "password" id="password" onblur="validate()"> <br><br>
retype password : <input type="password" id="retype_password" onblur="validate()"> <br><br>
<script>
function validate() {
var x= document.getElementById("password");
var y= document.getElementById("retype_password");
if(x.value==y.value) return;
else alert("password not same");
}
</script>
Please be careful with method names in JavaScript. The correct method for picking the element by name is document.getElementsByName which returns a NodeList. So in order to get the first field with the required name you should treat the result as array:
function validate() {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
}
alert('password not same');
return false;
}
To make the solution work correctly you have to bind the validation function as a <form> submit event (as an example):
var form = document.getElementById('myform');
form.addEventListener('submit', function() {
return validate();
}, false);
Or shorter as:
document.getElementById('myform').addEventListener('submit', validate, false);
If you don't have a form and use some button-like elements, you may bind a click event, e.g.:
var mybutton = document.getElementById('mybutton');
mybutton.addEventListener('click', function() {
if ( validate() ) {
// do AJAX request or whatever...
}
}, false);
Their are many ways to call this function.
You can add a new button :
<input type = 'button' value = 'validate' onclick = 'validate()' />
Or call the function when the focus on the text field is out :
<input type="password" name="retype_password" onblur = 'validate()' > <br><br>
Their are other ways to do (onkeydown, onchange...) check JS events to learn more : http://www.w3schools.com/jsref/dom_obj_event.asp
Right code from #VisioN :
function validate(event) {
var x = document.getElementsByName('password')[0].value,
y = document.getElementsByName('retype_password')[0].value;
if (x === y) {
return true;
} else {
alert('password not same');
event.preventDefault();
return false;
}
}
Add a onclick="validate(event);" attribute on the submit button.
(if validate return false, prevent the event from bubbling with event.preventDefault();).
EDIT
Maybe it is better tyo bind it to onSubmit event.
<form onsubmit="validate(event)">
Apolo
You have to use getElementById instead of getElementByName
Javascript:
function validate() {
var x = getElementById("password").value;
var y = getElementById("retype_password").value;
if(x==y) {
return true;
} else {
alert("password not same");
return false;
}
}
and html:
<form onsubmit="return validate();" action="submit_path" >
<input type= "password" id="password" name="password">
<input type= "password" id="retype_password" name="retype_password">
<input type="submit" name="submit" value="Submit" >
</form>
Here is an easier way by using class:
password : <input type= "password" class="passwords" name="password"> <br><br>
retype password : <input type="password" class="passwords" name="retype_password" > <br><br>
In your javascript:
var passwords = document.getElementsByClassName("passwords");
function validate(){
var first = passwords[0].value;
var second = passwords[1].value;
if(first != second){
//Invalid
} else{
//Valid
}
}

how to control the password fild with javascript

I am making a form for a website with javascript, and I am trying to control the password field. I am using this jscript function
function passcheck() {
var pass=document.getElementById('password');
if (pass.value.length<=6)
{alert("The password must me greater the");
}
}
and the form":
<input type="password" name="password1" onchange="passcheck()">
but it doesnt function.
what can I do? please help me
I solve it. NOw my function lokk like this
function passcheck() {
var pass=document.getElementById('password1');
if (pass.value.length<=6)
{alert("The password must me greater the");
}
}
But I would like to show the message not in a alert but I would like to show it at the right af the input..How can I do thi
Now I want to dissable the button when the password is less then 6 characters. I have done this function
function passcheck() {
var pass=document.getElementById('password1');
var sb=document.getElementById('submit');
if (pass.value.length<=6)
{document.getElementById('error').style.display = 'block';
sb.disable=true;}
else
{
sb.disable=false;
}
and the html part is this
<input type="password" name="password1" id="password1" class="textinput" onchange="passcheck()"><br>
<input type="button" value="Submit" id="submit" onclick="location.href='userlogin.html'" class="button" ><br>
but the button is still enablet... What can I do?
}
You dont have an ID on that element, a better way would be to pass in this in your inline handler, and add a param to your function:
<input type="password" name="password1" onchange="passcheck(this)">
function passcheck(elem) {
var pass = elem.value;
if (pass.value.length<=6)
{
alert("The password must me greater the");
}
}
Yoy should use, OnBlur, since it activates when the cursor leaves the textbox

Categories

Resources