1580524876
I have assumed that you have basic knowledge of Angular and have already created an Angular app. Here, I’ll show how to create a directive for confirming password validation and how to use it in your existing app.
Step 1
Create a folder named directive in your app’s root folder if it doesn’t already exist, and create a subfolder named compare-directive . We will create a directive in this subfolder.
Step 2
Create a directve named compare-password.directive using angular cli, or create a typescript file named compare-password.directive.ts inside the compare-directive folder, and paste the below code in the compare-password.directive.ts file.
import { Directive, Attribute } from '@angular/core';
import { Validator, NG_VALIDATORS } from '@angular/forms';
@Directive({
selector: '[compare-password]',
providers: [{provide: NG_VALIDATORS, useExisting: CompareDirective, multi: true}]
})
export class CompareDirective implements Validator {
constructor(@Attribute('compare-password') public comparer: string,
@Attribute('parent') public parent: string){}
validate(c: any): {[key: string]: any} {
const e = c.root.get(this.comparer);
if (e && c.value !== e.value && !this.isParent) {
return { compare: true };
}
if (e && c.value === e.value && this.isParent) {
delete e.errors['compare'];
if (!Object.keys(e.errors).length) {
e.setErrors(null);
}
}
if (e && c.value !== e.value && this.isParent) {
e.setErrors({ compare: true });
}
}
private get isParent() {
if (!this.parent) {
return false;
}
return this.parent === 'true' ? true : false;
}
}
In the above code snippet we have creted a custom directive with @Directive decorator. We have given selector value as compare-password, which means we can call this directive from the html element using selector value (i.e compare-password in this case).
This directive is accepting two attributes; the first is to provide the element with what we have to compare the value. The second one is to specify the element is the main parent element to the child element to which we have to compare the value.
At Line 30 we have added the element error name as compare if both values are not equal. We can use this error name to show or hide the error message or for form validation.
Step 3
Now we will create a module and will declare this directive in that module. That way we can directly import this module in any of the modules we want to use this directive. Create a module file named compare-password.module.ts and paste the below code.
import { NgModule } from '@angular/core';
// Directive
import { CompareDirective } from './compare-password.directive';
@NgModule({
declarations: [
CompareDirective
],
exports: [
CompareDirective
]
})
export class ComparePasswordModule { }
Here we have created a module and declared the directive in that module. Also we have exported the directive so we can use this directive after importing this module in another module.
Note We can directly declare this directive in app.module or any other module as well, instead of creating separate modules.
Step 4
We have created the directive successfully, now we will learn how to use this directive in another component. We will create a new component, register.component, and we will use our custom directive in this component.
Create a component named register-component.ts using angular cli or manually, and paste the below code.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-register',
templateUrl: './register.component.html'
})
export class RegisterUserComponent implements OnInit {
public user: User;
ngOnInit() {
this.user = {
username: '',
email: '',
password: '',
confirmPassword: ''
};
}
onSubmit(model: User) {
console.log(model);
}
}
export interface User {
username: string;
email: string;
password: string;
confirmPassword: string;
}
Here we have created a component and an interface as well to bind the form value using ngmodel.
Step 5
Here comes the main part to call the directive from the HTML Dom element. Paste the below code in register-component.html file.
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Register</div>
<form (ngSubmit)="onSubmit()" #frm="ngForm">
<div class="card-body">
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input type="text" [ngModel]='user.email' class="form-control" name="email">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">User Name</label>
<div class="col-md-6">
<input type="text" [ngModel]='user.username' class="form-control" name="username">
</div>
</div>
<div class="form-group row">
<label for="pass" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input type="password" [ngModel]='user.password' class="form-control" name="txtPassword" #txtPassword="ngModel" compare-password="txtConfirmPassword" parent="true" required>
<span class="text-danger" *ngIf="txtPassword.dirty && txtPassword.errors && txtPassword.errors.required">Password is required </span>
</div>
</div>
<div class="form-group row">
<label for="confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<input type="password" [ngModel]='user.confirmPassword' class="form-control" name="txtConfirmPassword" #txtConfirmPassword="ngModel" compare-password="txtPassword" required>
<span class="text-danger" *ngIf="txtConfirmPassword.dirty && txtConfirmPassword.errors && txtConfirmPassword.errors.required">Password is required </span>
<span class="text-danger" *ngIf="txtConfirmPassword.dirty && ((txtPassword.errors && txtPassword.errors.compare) || (txtConfirmPassword.errors && txtConfirmPassword.errors.compare)) && !txtConfirmPassword.errors.required">Password Doesn't match</span>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" [disabled]="!frm.isValid" class="btn btn-primary">
Register
</button>
</div>
</div>
</form >
</div>
</div>
</div>
</div>
Here at Line 23 for password textbox, we have specified the attribute compare-password=“txtConfirmPassword” parent=“true” which is the actual call of our custom directive. We have given the same name in attribute as we have mentioned in selector of directive. For confirming password we have called the directive at Line 30.
Note – for password textbox we have given the attribute compare-password as txtConfirmPassword
and for confirm password textbox as txtPassword
which means we have to specify the element name to which we want to compare the values.
The below code snippet is used to show and hide the error message when the password doesn’t match. Remember we have added the element error name as compare
if values are not equal while creating a directive in Step 2. Here we have used the same error name to display the error message.
<span class="text-danger" *ngIf="txtConfirmPassword.dirty && ((txtPassword.errors && txtPassword.errors.compare) || (txtConfirmPassword.errors && txtConfirmPassword.errors.compare)) && !txtConfirmPassword.errors.required">Password Doesn't match</span>
Step 6
At last we have to import the ComparePasswordModule created in Step 3. We have to import the module in the same module in which register-component is declared; i.e app.module.ts or another module.
Note
Also don’t forget to import FormModule and ReactiveFormsModule in the same module to use the ngmodel.
Thanks for reading this article. Let me know your feedback to enhance the quality of this article. Happy coding!!
#angular #javascript #confirmpassword
1680761100
If you are a beginner and want to create a JavaScript Password Generator then this tutorial is for you. Here I have shown step-by-step and shared complete information on how to create a password generator using JavaScript.
JavaScript Password Generator will help you create the password of your choice. Earlier I showed you how to create JavaScript Random Password Generator. However, this design will give you the option to create a password manually.
This simple password generator will help you create the password you want. There are different options and controls. This will allow you to create the password you need.
You need JavaScript enabled to view it to make it. Here I have used HTML CSS and some amount of JavaScript.
First, a box was created on the webpage. In that box, I first created a display where the generated passwords can be seen.
Then an input box is created where you can control the width of the password. This means that the number of characters you want to create the password can be controlled by this slider.
Then there are the four smaller boxes. This select box created by the checkbox will help you to further customize your password. There is a button at the end of which clicks on which the password is generated and can be seen in the display.
If you want to create this Password Generator JavaScript then you must have a basic idea about HTML, CSS, and javascript.
But if you just want the source code then follow the part below the article. But if you are a beginner then follow the tutorial below.
This JavaScript Password Generator has a copy button. When you click on the Generate button, the password will be copied automatically.
I first created an area using the following HTML and CSS codes. In this area, you can see all the information of Password Generator with JavaScript.
<div id=”password-generator”>
</div>
The webpage has been designed using the following code. Here the background color of the webpage is blue.
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
overflow: hidden;
margin: 0;
padding: 0;
display: flex;
align-items: center;
text-align: center;
height: 100vh;
background: #0976d5;
}
I have used the background color of this box as white and width: 500px. Box shadows have been used to enhance beauty.
#password-generator {
padding: 2rem;
margin: 0 auto;
width: 500px;
border-radius: 3px;
box-shadow: 0 0 2px #1f1f1f;
border: 3px solid #d5d4ff;
position: relative;
background: white;
white-space: nowrap;
}
Now we have created a display that will help to see the generated passwords. HTML’s input function has been used to create this box.
Box-shadow has been used to enhance the background white color and beauty of the box. Its box has no specific size. It will determine its own size depending on the amount of padding.
<input value=”Password generator” id=”password-output”>
input {
border: none;
background: transparent;
outline: none;
}
#password-output {
text-align: center;
font-size: 2rem;
margin: 0 auto 1.2rem;
width: 100%;
color: rgb(2, 91, 164);
padding: 5px;
box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
Now a range slider has been created in this JavaScript Password Generator. I have used two input boxes here. The first input box to create the slider and the second input box to create the display.
When you change the value of this range, the value in that display will change. The input boxes are connected to each other using JavaScript.
<div class=”range”>
<input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
oninput=”document.getElementById(‘display-password-length’).value=this.value”>
<input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
oninput=”document.getElementById(‘password-length’).value=this.value”>
</div>
#password-generator .range {
justify-content: space-between;
margin-top: 20px;
margin-bottom: 60px;
max-width: 70%;
margin-left: 15%;
padding: .4rem 1rem .8rem 2.5rem;
border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
-webkit-appearance: none;
appearance: none;
width: 40%;
max-width: 100%;
height: 15px;
padding: 0px;
background: #7a7a82;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
border-radius: 10px;
cursor: pointer;
scroll-behavior: smooth;
z-index: 1;
}
The Range Slider button has been designed using the following codes. Here I am using the background color blue of the button.
.range input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: rgb(9, 71, 222);
cursor: pointer;
border-radius: 18px;
transition: 0.5s ease;
}
The size of the display is determined using the CSS below. Font-size: 1.4rem has been used to increase the display’s width: 80px and text size.
body #password-generator .range #display-password-length {
text-align: center;
font-size: 1.4rem;
width: 80px;
padding-top: 10px;
}
The select options have been created using the following codes. Here four inputs and four labels are used. There is a label for each input.
Those labels will help to understand which select box to select which value. You can customize your password using this select box.
<div class=”flex”>
<input type=”checkbox” id=”lowercase” checked=”checked”>
<label for=”lowercase”>a-z</label>
<input type=”checkbox” id=”uppercase”>
<label for=”uppercase”>A-Z</label>
<input type=”checkbox” id=”numbers”>
<label for=”numbers”>0-9</label>
<input type=”checkbox” id=”symbols”>
<label for=”symbols”>!-?</label>
</div>
.flex {
margin: 1rem 1rem 2rem;
display: flex;
justify-content: space-between;
}
.flex input {
display: none;
}
.flex input:checked + label {
border: 2px solid rgb(205, 151, 12);
background: rgb(173, 144, 82);
filter: brightness(120%);
transform: scale(1.1);
}
.flex label {
border: 2px solid #0571bb;
border-radius: 4px;
padding: 0.6rem;
cursor: pointer;
font-size: 1.3rem;
text-align: center;
display: block;
width: 80px;
transition: 0.2s ease;
}
Now you need to create a button in Password Generator JavaScript. The password will be generated when the button is clicked.
Here the button function is used. The button’s background color is blue and the text color is white.
<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
outline: none;
background: #0f6cc3;
color: white;
border: none;
padding: 1rem 2rem;
margin: 0.5rem 0;
border-radius: 3px;
box-shadow: 1px 1px 6px 1px #8f8a8a;
text-transform: uppercase;
font-size: 1.2rem;
transition: 0.2s ease;
cursor: pointer;
}
#password-generator button:hover {
background: rgb(173, 118, 22);
}
I have basically designed this JavaScript Password Generator above. Now it’s time to activate this password generator using JavaScript.
JavaScript used here is a bit difficult. To understand these codes you need to have a basic idea about JavaScript.
//The global constant of the display id is set
const passwordOutput = document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
const data = [].concat(
lowercase.checked ? dataLowercase : [],
uppercase.checked ? dataUppercase : [],
numbers.checked ? dataNumbers : [],
symbols.checked ? dataSymbols : []
);
//The value obtained from the range slider is stored in ‘password Length’
let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
let newPassword = ”;
//If you do not select a select box, you will see the following alert message
if (data.length === 0) {
passwordOutput.innerHTML = “Générateur de MDP”;
alert(‘Please check at least one criteria’);
return;
}
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
for (let i = 0; i < passwordLength; i++) {
newPassword += data[Math.floor(Math.random() * data.length)];
}
//Arrangements have been made to display the value of the new password in the display
passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
passwordOutput.select();
document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
There are many users who just want the source code. Below I have given all the source code for them together. If you want to take all the code of this JavaScript Password Generator together then use the section below.
Here HTML, CSS, and javascript code are together. You copy those codes and add them to your HTML file. If you want previews and tutorials then follow the article above.
Hopefully using the above codes you have learned how to create this password generator using JavaScript. Earlier I shared a tutorial on Random Password Generator.
If you want to create a simple password generator then you can follow that tutorial. Below is a button that allows you to download the source code. If there is any problem, you can let me know by commenting.
Original article source at: https://foolishdeveloper.com/
1620578087
In this post I will show you how to validate password and confirm password using jQuery, Validation is basic and important feature for authentication user so here i will give you demo about password and confirm password validation using jquery.
In jquery we are using keyup event to check whether password and confirm password is match or not.
#javascript #jquery #validation #validate password and confirm password #validate password in jquery #validate password and confirm password in jquery
1680768780
Если вы новичок и хотите создать генератор паролей JavaScript , то это руководство для вас. Здесь я пошагово показал и поделился полной информацией о том, как создать генератор паролей с помощью JavaScript .
Генератор паролей JavaScript поможет вам создать пароль по вашему выбору. Ранее я показал вам, как создать генератор случайных паролей JavaScript . Однако этот дизайн даст вам возможность создать пароль вручную.
Этот простой генератор паролей поможет вам создать пароль, который вы хотите. Есть разные опции и элементы управления. Это позволит вам создать пароль, который вам нужен.
У вас должен быть включен JavaScript, чтобы просмотреть его, чтобы сделать это. Здесь я использовал HTML CSS и немного JavaScript.
Сначала на веб-странице был создан ящик. В этом поле я сначала создал дисплей, на котором можно увидеть сгенерированные пароли .
Затем создается поле ввода, в котором вы можете контролировать ширину пароля. Это означает, что количество символов, которые вы хотите создать в пароле, можно контролировать с помощью этого ползунка.
Затем идут четыре меньших коробки. Это поле выбора, созданное флажком, поможет вам дополнительно настроить свой пароль. В конце есть кнопка, при нажатии на которую генерируется пароль, который можно увидеть на дисплее.
Если вы хотите создать этот JavaScript-генератор паролей , у вас должно быть базовое представление о HTML, CSS и javascript.
Но если вам просто нужен исходный код, следуйте инструкциям ниже. Но если вы новичок, следуйте инструкциям ниже.
Этот генератор паролей JavaScript имеет кнопку копирования. При нажатии на кнопку «Создать» пароль будет скопирован автоматически.
Сначала я создал область, используя следующие коды HTML и CSS. В этой области вы можете увидеть всю информацию о генераторе паролей с JavaScript.
<div id=”password-generator”>
</div>
Веб-страница была разработана с использованием следующего кода. Здесь цвет фона веб-страницы синий.
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
overflow: hidden;
margin: 0;
padding: 0;
display: flex;
align-items: center;
text-align: center;
height: 100vh;
background: #0976d5;
}
Я использовал цвет фона этого поля как белый и ширину: 500 пикселей. Коробчатые тени использовались для усиления красоты.
#password-generator {
padding: 2rem;
margin: 0 auto;
width: 500px;
border-radius: 3px;
box-shadow: 0 0 2px #1f1f1f;
border: 3px solid #d5d4ff;
position: relative;
background: white;
white-space: nowrap;
}
Теперь мы создали дисплей, который поможет увидеть сгенерированные пароли. Для создания этого поля использовалась функция ввода HTML.
Box-shadow был использован для улучшения белого цвета фона и красоты блока. Его коробка не имеет определенного размера. Он сам определит свой размер в зависимости от количества отступов.
<input value=”Password generator” id=”password-output”>
input {
border: none;
background: transparent;
outline: none;
}
#password-output {
text-align: center;
font-size: 2rem;
margin: 0 auto 1.2rem;
width: 100%;
color: rgb(2, 91, 164);
padding: 5px;
box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
Теперь в этом генераторе паролей JavaScript создан ползунок диапазона . Здесь я использовал два поля ввода. Первое поле ввода для создания ползунка и второе поле ввода для создания дисплея.
Когда вы измените значение этого диапазона, значение на этом дисплее изменится. Поля ввода связаны друг с другом с помощью JavaScript.
<div class=”range”>
<input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
oninput=”document.getElementById(‘display-password-length’).value=this.value”>
<input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
oninput=”document.getElementById(‘password-length’).value=this.value”>
</div>
#password-generator .range {
justify-content: space-between;
margin-top: 20px;
margin-bottom: 60px;
max-width: 70%;
margin-left: 15%;
padding: .4rem 1rem .8rem 2.5rem;
border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
-webkit-appearance: none;
appearance: none;
width: 40%;
max-width: 100%;
height: 15px;
padding: 0px;
background: #7a7a82;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
border-radius: 10px;
cursor: pointer;
scroll-behavior: smooth;
z-index: 1;
}
Кнопка Range Slider была разработана с использованием следующих кодов. Здесь я использую синий цвет фона кнопки.
.range input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: rgb(9, 71, 222);
cursor: pointer;
border-radius: 18px;
transition: 0.5s ease;
}
Размер дисплея определяется с помощью приведенного ниже CSS. Размер шрифта: 1.4rem был использован для увеличения ширины экрана: 80 пикселей и размера текста.
body #password-generator .range #display-password-length {
text-align: center;
font-size: 1.4rem;
width: 80px;
padding-top: 10px;
}
Опции выбора были созданы с использованием следующих кодов. Здесь используются четыре входа и четыре метки. Для каждого входа есть метка.
Эти метки помогут понять, в каком поле выбора выбрать какое значение. Вы можете настроить свой пароль , используя это поле выбора.
<div class=”flex”>
<input type=”checkbox” id=”lowercase” checked=”checked”>
<label for=”lowercase”>a-z</label>
<input type=”checkbox” id=”uppercase”>
<label for=”uppercase”>A-Z</label>
<input type=”checkbox” id=”numbers”>
<label for=”numbers”>0-9</label>
<input type=”checkbox” id=”symbols”>
<label for=”symbols”>!-?</label>
</div>
.flex {
margin: 1rem 1rem 2rem;
display: flex;
justify-content: space-between;
}
.flex input {
display: none;
}
.flex input:checked + label {
border: 2px solid rgb(205, 151, 12);
background: rgb(173, 144, 82);
filter: brightness(120%);
transform: scale(1.1);
}
.flex label {
border: 2px solid #0571bb;
border-radius: 4px;
padding: 0.6rem;
cursor: pointer;
font-size: 1.3rem;
text-align: center;
display: block;
width: 80px;
transition: 0.2s ease;
}
Теперь вам нужно создать кнопку в генераторе паролей JavaScript. Пароль будет сгенерирован при нажатии на кнопку.
Здесь используется функция кнопки. Цвет фона кнопки — синий, а цвет текста — белый.
<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
outline: none;
background: #0f6cc3;
color: white;
border: none;
padding: 1rem 2rem;
margin: 0.5rem 0;
border-radius: 3px;
box-shadow: 1px 1px 6px 1px #8f8a8a;
text-transform: uppercase;
font-size: 1.2rem;
transition: 0.2s ease;
cursor: pointer;
}
#password-generator button:hover {
background: rgb(173, 118, 22);
}
Я в основном разработал этот генератор паролей JavaScript выше. Теперь пришло время активировать этот генератор паролей с помощью JavaScript .
Используемый здесь JavaScript немного сложен. Чтобы понять эти коды, вам нужно иметь базовое представление о JavaScript .
//The global constant of the display id is set
const passwordOutput = document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
const data = [].concat(
lowercase.checked ? dataLowercase : [],
uppercase.checked ? dataUppercase : [],
numbers.checked ? dataNumbers : [],
symbols.checked ? dataSymbols : []
);
//The value obtained from the range slider is stored in ‘password Length’
let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
let newPassword = ”;
//If you do not select a select box, you will see the following alert message
if (data.length === 0) {
passwordOutput.innerHTML = “Générateur de MDP”;
alert(‘Please check at least one criteria’);
return;
}
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
for (let i = 0; i < passwordLength; i++) {
newPassword += data[Math.floor(Math.random() * data.length)];
}
//Arrangements have been made to display the value of the new password in the display
passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
passwordOutput.select();
document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
Есть много пользователей, которые просто хотят исходный код. Ниже я привел весь исходный код для них вместе. Если вы хотите собрать весь код этого генератора паролей JavaScript вместе, воспользуйтесь разделом ниже.
Здесь HTML, CSS и код javascript объединены. Вы копируете эти коды и добавляете их в свой HTML-файл. Если вам нужны предварительные просмотры и учебные пособия, следуйте статье выше.
Надеюсь, используя приведенные выше коды, вы научились создавать этот генератор паролей с помощью JavaScript. Ранее я поделился туториалом по генератору случайных паролей .
Если вы хотите создать простой генератор паролей , вы можете следовать этому руководству. Ниже находится кнопка, позволяющая загрузить исходный код. Если есть какие-либо проблемы, вы можете сообщить мне, комментируя.
Оригинальный источник статьи: https://foolishdeveloper.com/
1680764941
如果您是初学者并想创建一个JavaScript 密码生成器,那么本教程适合您。在这里,我逐步展示并分享了有关如何使用 JavaScript 创建密码生成器的完整信息。
JavaScript 密码生成器将帮助您创建您选择的密码。之前我向您展示了如何创建JavaScript 随机密码生成器。但是,此设计将为您提供手动创建密码的选项。
这个简单的密码生成器将帮助您创建您想要的密码。有不同的选项和控件。这将允许您创建所需的密码。
您需要启用 JavaScript 才能查看它。这里我使用了 HTML CSS 和一些 JavaScript。
首先,在网页上创建了一个框。在那个框中,我首先创建了一个可以看到 生成的密码的显示。
然后创建一个输入框,您可以在其中控制密码的宽度。这意味着您可以通过此滑块控制要创建密码的字符数。
然后是四个较小的盒子。这个由复选框创建的选择框将帮助您进一步自定义您的密码。在其末尾有一个按钮,单击该按钮将生成密码并可以在显示屏上看到。
如果你想创建这个密码生成器 JavaScript,那么你必须对 HTML、CSS 和 javascript 有基本的了解。
但如果您只想要源代码,请按照文章下方的部分进行操作。但是,如果您是初学者,请按照下面的教程进行操作。
这个JavaScript 密码生成器有一个复制按钮。当您点击生成按钮时,密码将被自动复制。
我首先使用以下 HTML 和 CSS 代码创建了一个区域。在此区域中,您可以看到 Password Generator with JavaScript 的所有信息。
<div id=”password-generator”>
</div>
该网页是使用以下代码设计的。这里网页的背景颜色是蓝色。
* {
box-sizing: border-box;
font-family: sans-serif;
}
body {
overflow: hidden;
margin: 0;
padding: 0;
display: flex;
align-items: center;
text-align: center;
height: 100vh;
background: #0976d5;
}
我使用这个框的背景颜色为白色和宽度:500px。盒子阴影已被用来增强美感。
#password-generator {
padding: 2rem;
margin: 0 auto;
width: 500px;
border-radius: 3px;
box-shadow: 0 0 2px #1f1f1f;
border: 3px solid #d5d4ff;
position: relative;
background: white;
white-space: nowrap;
}
现在我们已经创建了一个显示,可以帮助查看生成的密码。HTML 的输入功能已用于创建此框。
box-shadow 已被用来增强盒子的背景白色和美感。它的盒子没有具体的尺寸。它将根据填充量确定自己的大小。
<input value=”Password generator” id=”password-output”>
input {
border: none;
background: transparent;
outline: none;
}
#password-output {
text-align: center;
font-size: 2rem;
margin: 0 auto 1.2rem;
width: 100%;
color: rgb(2, 91, 164);
padding: 5px;
box-shadow: 0 0 20px rgba(0,139,253,0.45);
}
现在,已在此JavaScript 密码生成器中创建了一个范围滑块。我在这里使用了两个输入框。第一个输入框创建滑块,第二个输入框创建显示。
当您更改此范围的值时,该显示中的值将更改。输入框使用 JavaScript 相互连接。
<div class=”range”>
<input type=”range” min=”4″ max=”24″ step=”1″ value=”8″ id=”password-length”
oninput=”document.getElementById(‘display-password-length’).value=this.value”>
<input type=”text” value=”8″ maxlength=”2″ id=”display-password-length”
oninput=”document.getElementById(‘password-length’).value=this.value”>
</div>
#password-generator .range {
justify-content: space-between;
margin-top: 20px;
margin-bottom: 60px;
max-width: 70%;
margin-left: 15%;
padding: .4rem 1rem .8rem 2.5rem;
border: 1.5px solid rgb(8, 84, 181);
}
#password-generator .range input[type=range] {
-webkit-appearance: none;
appearance: none;
width: 40%;
max-width: 100%;
height: 15px;
padding: 0px;
background: #7a7a82;
outline: none;
opacity: 0.7;
-webkit-transition: 0.2s;
transition: opacity 0.2s;
box-shadow: 0 2px 35px rgba(0, 0, 0, 0.4555);
border-radius: 10px;
cursor: pointer;
scroll-behavior: smooth;
z-index: 1;
}
Range Slider 按钮是使用以下代码设计的。这里我使用了按钮的背景色蓝色。
.range input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: rgb(9, 71, 222);
cursor: pointer;
border-radius: 18px;
transition: 0.5s ease;
}
显示的大小是使用下面的 CSS 确定的。字体大小:1.4rem 已用于增加显示宽度:80px 和文本大小。
body #password-generator .range #display-password-length {
text-align: center;
font-size: 1.4rem;
width: 80px;
padding-top: 10px;
}
选择选项是使用以下代码创建的。这里使用了四个输入和四个标签。每个输入都有一个标签。
这些标签将有助于理解哪个选择框选择哪个值。您可以使用此选择框自定义您的密码。
<div class=”flex”>
<input type=”checkbox” id=”lowercase” checked=”checked”>
<label for=”lowercase”>a-z</label>
<input type=”checkbox” id=”uppercase”>
<label for=”uppercase”>A-Z</label>
<input type=”checkbox” id=”numbers”>
<label for=”numbers”>0-9</label>
<input type=”checkbox” id=”symbols”>
<label for=”symbols”>!-?</label>
</div>
.flex {
margin: 1rem 1rem 2rem;
display: flex;
justify-content: space-between;
}
.flex input {
display: none;
}
.flex input:checked + label {
border: 2px solid rgb(205, 151, 12);
background: rgb(173, 144, 82);
filter: brightness(120%);
transform: scale(1.1);
}
.flex label {
border: 2px solid #0571bb;
border-radius: 4px;
padding: 0.6rem;
cursor: pointer;
font-size: 1.3rem;
text-align: center;
display: block;
width: 80px;
transition: 0.2s ease;
}
现在您需要在密码生成器 JavaScript 中创建一个按钮。单击按钮时将生成密码。
这里使用了按钮功能。按钮的背景颜色为蓝色,文本颜色为白色。
<button id=”generateButton” type=”button” onclick=”generatePassword()”>Generate</button>
#password-generator button {
outline: none;
background: #0f6cc3;
color: white;
border: none;
padding: 1rem 2rem;
margin: 0.5rem 0;
border-radius: 3px;
box-shadow: 1px 1px 6px 1px #8f8a8a;
text-transform: uppercase;
font-size: 1.2rem;
transition: 0.2s ease;
cursor: pointer;
}
#password-generator button:hover {
background: rgb(173, 118, 22);
}
我基本上已经设计了上面的这个JavaScript密码生成器。现在是时候使用 JavaScript激活这个密码生成器了。
这里使用的 JavaScript 有点难。要理解这些代码,您需要对 JavaScript 有一个基本的了解。
//The global constant of the display id is set
const passwordOutput = document.getElementById(‘password-output’);
//The Lower characters used here are stored in the ‘dataLowercase’
const dataLowercase = “azertyuiopqsdfghjklmwxcvbn”.split(”);
//The Upper characters used here are stored in the ‘dataUppercase’
const dataUppercase = “AZERTYUIOPQSDFGHJKLMWXCVBN”.split(”);
//The Numbers used here are stored in the ‘dataNumbers’
const dataNumbers = “0123456789”.split(”);
//The Symbols used here are stored in the ‘dataSymbols’
const dataSymbols = “!@#$%^&*-_=+\|:;’,.>/?~”.split(”);
function generatePassword() {
//concat() is a string method that is used to concatenate strings together
const data = [].concat(
lowercase.checked ? dataLowercase : [],
uppercase.checked ? dataUppercase : [],
numbers.checked ? dataNumbers : [],
symbols.checked ? dataSymbols : []
);
//The value obtained from the range slider is stored in ‘password Length’
let passwordLength = parseInt(document.getElementById(‘display-password-length’).value);
let newPassword = ”;
//If you do not select a select box, you will see the following alert message
if (data.length === 0) {
passwordOutput.innerHTML = “Générateur de MDP”;
alert(‘Please check at least one criteria’);
return;
}
//It has been decided in which format the generated password will be displayed
//The Math. random() function returns a floating-point in the range 0 to less than 1
for (let i = 0; i < passwordLength; i++) {
newPassword += data[Math.floor(Math.random() * data.length)];
}
//Arrangements have been made to display the value of the new password in the display
passwordOutput.value = newPassword;
//The copy button has been activated.
//Clicking the Generate button will automatically copy the password
passwordOutput.select();
document.execCommand(‘copy’);
//After copying the password, the following text will appear in the button
generateButton.innerHTML = “Copied !”;
//Arrangements have been made to change the text of the button after 3.5 seconds
setTimeout(() => {generateButton.innerHTML = “Generator Again”}, 3500);
}
有很多用户只想要源代码。下面我把它们的所有源码都一并给出了。如果您想将此 JavaScript密码生成器的所有代码放在一起,请使用下面的部分。
这里 HTML、CSS 和 javascript 代码在一起。您复制这些代码并将它们添加到您的 HTML 文件中。如果您想要预览和教程,请按照上面的文章进行操作。
希望通过上面的代码,您已经了解了如何使用 JavaScript 创建此密码生成器。早些时候我分享了一个关于随机密码生成器的教程。
如果您想创建一个简单的密码生成器,那么您可以按照该教程进行操作。下面是一个允许您下载源代码的按钮。如果有任何问题,您可以通过评论让我知道。
文章原文出处:https: //foolishdeveloper.com/
1656193861
Hello guys, Today in this post we’ll learn How to Create a Simple Login Page with a fantastic design. To create it we are going to use pure CSS and HTML. Hope you enjoy this post.
A login page is one of the most important component of a website or app that allows authorized users to access an entire site or a part of a website. You would have already seen them when visiting a website. Let's head to create it.
Whether it’s a signup or login page, it should be catchy, user-friendly and easy to use. These types of Forms lead to increased sales, lead generation, and customer growth.
Demo
Click to watch demo!
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="styledfer.css">
</head>
<body>
<div id="login-form-wrap">
<h2>Login</h2>
<form id="login-form">
<p>
<input type="email" id="email" name="email" placeholder="Email " required><i class="validation"><span></span><span></span></i>
</p>
<p>
<input type="password" id="password" name="password" placeholder="Password" required><i class="validation"><span></span><span></span></i>
</p>
<p>
<input type="submit" id="login" value="Login">
</p>
</form>
<div id="create-account-wrap">
<p>Don't have an accout? <a href="#">Create One</a><p>
</div>
</div>
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js'></script>
</body>
</html>
body {
background-color: #020202;
font-size: 1.6rem;
font-family: "Open Sans", sans-serif;
color: #2b3e51;
}
h2 {
font-weight: 300;
text-align: center;
}
p {
position: relative;
}
a,
a:link,
a:visited,
a:active {
color: #ff9100;
-webkit-transition: all 0.2s ease;
transition: all 0.2s ease;
}
a:focus, a:hover,
a:link:focus,
a:link:hover,
a:visited:focus,
a:visited:hover,
a:active:focus,
a:active:hover {
color: #ff9f22;
-webkit-transition: all 0.2s ease;
transition: all 0.2s ease;
}
#login-form-wrap {
background-color: #fff;
width: 16em;
margin: 30px auto;
text-align: center;
padding: 20px 0 0 0;
border-radius: 4px;
box-shadow: 0px 30px 50px 0px rgba(0, 0, 0, 0.2);
}
#login-form {
padding: 0 60px;
}
input {
display: block;
box-sizing: border-box;
width: 100%;
outline: none;
height: 60px;
line-height: 60px;
border-radius: 4px;
}
#email,
#password {
width: 100%;
padding: 0 0 0 10px;
margin: 0;
color: #8a8b8e;
border: 1px solid #c2c0ca;
font-style: normal;
font-size: 16px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
position: relative;
display: inline-block;
background: none;
}
#email:focus,
#password:focus {
border-color: #3ca9e2;
}
#email:focus:invalid,
#password:focus:invalid {
color: #cc1e2b;
border-color: #cc1e2b;
}
#email:valid ~ .validation,
#password:valid ~ .validation
{
display: block;
border-color: #0C0;
}
#email:valid ~ .validation span,
#password:valid ~ .validation span{
background: #0C0;
position: absolute;
border-radius: 6px;
}
#email:valid ~ .validation span:first-child,
#password:valid ~ .validation span:first-child{
top: 30px;
left: 14px;
width: 20px;
height: 3px;
-webkit-transform: rotate(-45deg);
transform: rotate(-45deg);
}
#email:valid ~ .validation span:last-child
#password:valid ~ .validation span:last-child
{
top: 35px;
left: 8px;
width: 11px;
height: 3px;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
}
.validation {
display: none;
position: absolute;
content: " ";
height: 60px;
width: 30px;
right: 15px;
top: 0px;
}
input[type="submit"] {
border: none;
display: block;
background-color: #ff9100;
color: #fff;
font-weight: bold;
text-transform: uppercase;
cursor: pointer;
-webkit-transition: all 0.2s ease;
transition: all 0.2s ease;
font-size: 18px;
position: relative;
display: inline-block;
cursor: pointer;
text-align: center;
}
input[type="submit"]:hover {
background-color: #ff9b17;
-webkit-transition: all 0.2s ease;
transition: all 0.2s ease;
}
#create-account-wrap {
background-color: #eeedf1;
color: #8a8b8e;
font-size: 14px;
width: 100%;
padding: 10px 0;
border-radius: 0 0 4px 4px;
}
Congratulations! You have now successfully created our Simple Login Page in HTML and CSS.
My Website: codewithayan, see this to checkout all of my amazing Tutorials.