I am trying to make the JavaScript have a min length on the username characters. The username has to have at least 5 characters in the name. So far, I can type in the username but, still get the message we need 5 characters even if we have more or less, the only time that does not happen is when I don't type anything in. I don't quite understand why.
// version 1
let y = document.querySelector("#nick2").value; {
if(y== 0)
for(y.length=0; y.length>5; y.length++);
{
console.log("need at least 5 letters in the username ");
}
//Version 2
let y = document.querySelector("#nick2").value; {
if(y== 0)
if(y.value.length !=5){
y.value="";
input=y.value
if(input.length<5){
console.log("need at least 5 letters in the username");
}
}
What am I doing wrong?
You can check the length of your input element by calling a function within your input element's onkeyup method.
Something like this:
function check(item) {
let y = item.value.trim(); // trim() removes any extra whitespace
if(y.length < 5) {
console.log("Need at least 5 letters in username");
} else {
console.log("You've entered 5 or more characters for username");
}
}
<!-- You can pass the element as 'this' to the function -->
<input type="text" value="" onkeyup="check(this)" />
Note: If you want to allow whitespace characters (spaces) to be a valid input then remove trim().
Related
I don't want to disable the input box, I'd like to either delete the bad character or allow the user to delete it.
So far I've tried to set the max length of the input to the length where the bad character was entered, but I was still able to type after that.
Here is a sample of the function I'm working on:
function validateCharacterName() {
var value = document.getElementById("characterName").value;
var message = document.getElementById("characterNameMessage");
var button = document.getElementById("confirmButton")
if (value.length <= 1) {
message.innerText = "Name must be two or more characters."
disableButton(button)
} else {
for (var counter = 0 ; counter < value.length; counter++) {
var character = value.charAt(counter);
if (isAlpha(character) && !isDigit(character)) {
message.innerText = "";
enableButton(button);
} else {
message.innerText = "Character '" + character + "' is invalid.";
disableButton(button);
}
}
}
}
The recommended way to ensure the entered text only contains expected characters is using the the pattern attribute. This works slightly different than you suggest, but will be more in line of what the user would expect, as it is a very common way how to do this. Here you can see this in action.
To be specific here is an example how you avoid the letter "a":
<input type="text" pattern="[^a]*" title="Please avoid the letter 'a'">
The pattern attribute uses regular expressions. This does need some getting used to, but is rather powerful. In this case the ^ insider the [] means "not". The a means "a" and the * means allow any number of appearances of the previous thing. In summary this means allow any number of any character not being an "a".
You might want to use a whitelist approach rather than a blacklist approach. For example to allow any Latin letters you could use:
<input type="text" pattern="[a-zA-Z]*" title="Please use letters only">
i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to be able to accept any way that a user inputs their phone number. I need help to include regular expressions that can validate the length of a number, bracket, hyphens and take care of spaces.
<script>
function Myfuc() {
var x = document.forms[0]["mobile"].value;
var z = document.forms[0]["mobile1"].value;
if(x == null || x == '')
{
alert("Field canot be empty");
return false;
}
if(x[0]!=0) // Starting with zero
{
alert("Mobile number should start with Zero");
return false;
}
var y=isNaN(x); // Checking numerals in first text box
if(y == true)
{
alert("Integers only accepted");
return false;
}
var z1=isNaN(z); // Checking numerals in first text box
if(z1 == true)
{
alert("Integers only accepted");
return false;
}
}
</script>
<form onsubmit="Myfuc()">
Mobile : <input type="text" id="mobile" name="mobile" style="width:40px;" maxlength=3> -
<input type="text" name="mobile1" maxlength=7>
<input type="submit" value="Click" name="sub" >
</form>
Everything you asked is here!!!, Spent 1 hr for this and imma beginner, dont worry code works well :-)
You could use this reg expression. I'm not too good with reg expressions but this could work in your case.
0\d{2}-\d{7}
/* start match with 0
check for 2 additional digits
check for hyphen
check for 7 additional digits after hyphen
*/
I also suck at creating regex expressions; however, you can always do something like this:
var str = document.getElementById('myInput').value,
numberOnly = str.replace(/-/g, ''),
errors = [], i;
if (isNaN(numberOnly)) {
errors.push('You must use numbers!');
} else if (str.split('-')[0].length !== 3 || str.split('-')[1] !== 7 || numberOnly > 10) {
errors.push('Invalid Format!');
} else {
console.log(numberOnly + ' is ok!');
}
if (errors) {
for (i = 0; i < errors.length; i++) {
console.log(i + '. ' + errors[i]);
}
}
It's simply testing each part of the string that is submitted.
First it checks to see (after we remove the hyphen) that the submitted value is actually a number.
Second, it splits the string in half to check if the start of the string has 3 characters, and then if the end of the string has 7 characters; lastly, it tests to see if the number is too large... etc, you can even check if its too small.
If you ever figure out a decent regex, you could instead use a switch statement to catch the errors (if any).
I think one might look like, [0-9]{3}(-)[0-9]{7} or something like that lol.
-
I've been working with PHP for awhile, so I forget if "length" returns a count, or the actual byte-size of a character, e.g. "é" is 2 bytes.
EDIT:
To check if the first character of the string is "0", you can always do:
if (str.length > 0 && str.charAt(0) != 0) { console.log('error'); }
I have been attempting to validate an australian phone number using javascript however it has been accepting everything. It needs to be 10 numbers long beginning with 0 accepting spaces:
02 4345 2334
and together
0243452334.
I think the regex might be wrong or the code itself
function PhoneNumberVal(form){
var phoneFormat= /^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$/;
var phoneLength = document.getElementById('phone').value.length;
if(phoneFormat.test(phoneLength)) {
return true;
} else {
alert("Not a valid phone number");
return false;
}
}
Your regex is wrong. ^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$ you failed to put the opening parenthesis and you need to change [0-8]{2} to [0-8], since your input contains exactly 10 digits.
^(?:\(0[0-8]\)|0[0-8])[ ]?[0-9]{4}[ ]?[0-9]{4}$
DEMO
Use this Regex,
/^\D*0(\D*\d){9}\D*$/
Demo
Regex? Ha! Now you have two problems.
UPDATE: This version should be final.
Just do this:
function IsAustralianTelephoneNumberValid(a_telephone)
{
a_telephone = a_telephone.replace(/\s/g, ''); // remove all spaces
// if is empty OR first char is NOT 0
if((a_telephone=='')||(a_telephone.charAt(0)!='0'))
{
alert("Not a valid phone number");
return false;
}
// lets save the length of that string before we remove digits
length_with_digits = a_telephone.length;
// now string has its digits removed
a_telephone = a_telephone.replace(/0|1|2|3|4|5|6|7|8|9/g,'');
// if is nothing, then there was no other characters in string
// except digits and spaces AND ALSO if the difference of length before the digits
// removal and now is 10 then we can be sure we had 10 digits and nothing else,
// so its valid. Any other case is not valid.
if((a_telephone=='')&&(length_with_digits-a_telephone.length==10))
{
alert('ok');
return true;
}
else
{
alert("Not a valid phone number");
return false;
}
}
http://jsfiddle.net/L7vzL4jm/10/
First i'd like to mention that i've been researching about this for few days and although i found some answers that should have been helpful i was unable to use them correctly due to the fact that i am not that much into programming yet and got no experience and might be missing something.
Straight to the point, i have a registration form and i need field validation i already have the one that validate email and empty fields for others but i need to add to the code a part that would reject numerical entries in name fields and alphabetical characters for ID field and to limit the length of a field.
Let's start with the Name field which i want to allow alphabetical characters only here is my current code:
{
var fn=document.forms["myForm"]["FirstName"].value;
if (fn==null || fn=="")
{
alert("First name must be filled out");
return false;
}
And that's my ID field which i want to limit to numerical entries only
var id=document.forms["myForm"]["ID"].value;
if (id==null || id=="")
{
alert("ID must be filled out");
return false;
}
I want to a couple of lines that would limit entries to a specific number of characters as well, how do i do that?
To check for a string length in Javascript you can use the .length method:
// this checks if the fn length is more than 10
if (fn.length > 10) {
}
To check if a value is numeric you can parse it and make sure that returns a valid output:
// This checks if id is not a valid integer
if (isNaN(parseInt(id)) {
}
To check if a value is alphabetical only you have to make sure the characters in it fall within the alphabets range, you can add a function that checks for that:
// This loops on every character of value and makes sure it is part of the letters string
function isAlphabetical (value) {
var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < value.length; i++) {
if (letters.indexOf(value.charAt(i), 0) == -1) {
return false;
}
return true;
}
}
And then call it from your if statement:
// This checks if fn is not alphabetical
if (!isAlphabetical(fn)) {
}