Password validation in Vue 3 isn't working properly - javascript

Making a registration form for a website using Vue 3. I have a method, that gets values of password and password confirmation fields and compares it. If they're true - nothing happens, else - a red label appears and submit button gets disabled. I have implemented this in vue 3. but when passwords are equal, it dont works, but sometimes when they are not, it displays that they are.
<template>
<div>
<label for="password">Пароль</label>
<input type="text" v-model="password" name="password" id="password" placeholder="••••••••" required="">
</div>
<div>
<label for="confirm-password">Подтвердите Пароль</label>
<input #keydown="confirmPassword" type="confirm-password" v-model="confirm" name="confirm-password" id="confirm-password" placeholder="••••••••" required="">
<label for="confirm-password" v-if="invalidPasswords">Пароли не совпадают</label>
</div>
<button :disabled="submitDisabled" type="submit">Создать аккаунт</button>
</template>
<script>
export default {
name: "RegistrationView",
data () {
return {
...
password: '',
confirm: '',
invalidPasswords: false,
submitDisabled: false,
}
},
methods: {
confirmPassword() {
if (this.password !== this.confirm){
this.invalidPasswords = true
this.submitDisabled = true
} else {
this.invalidPasswords = false
this.submitDisabled = false
}
},
},
}
</script>
Screenshots: https://i.stack.imgur.com/3eOB1.png https://i.stack.imgur.com/ein5h.png https://i.stack.imgur.com/ein5h.png

Just change #keydown event to #input :
<input #input="confirmPassword" type="confirm-password" v-model="confirm" name="confirm-password" id="confirm-password" placeholder="••••••••" required="">

You can use #keyup or #input instead of #keydown in your confirm password:
<input #keyup="confirmPassword" type="confirm-password" v-model="confirm" name="confirm-password" id="confirm-password" placeholder="••••••••" required="">
OR
<input #input="confirmPassword" type="confirm-password" v-model="confirm" name="confirm-password" id="confirm-password" placeholder="••••••••" required="">
Both work fine.

Related

Why are my required inputs being highlighted before the user enters text?

I am building a React component that contains a login/registration form. Which form displays is determined by the user by clicking on the relevant tab, which updates the values of reg and log in state. However, my issue is that if the user enters text into the first two inputs of either form, if they toggle to the other form, the first two inputs of that form will be highlighted red, even though the user hasn't entered anything into those inputs. I have taken some screenshots to demonstrate what I mean:
Is anybody able to explain why this is happening? It's only a small issue, but I'd like to at least understand why it's happening :)
Here is the form inside the render() method of the component:
<aside className="logReg">
<ul className="tabGroup">
<li className={`tab${this.state.reg ? " active" : ""}`} onClick={this.handleClick}>Register</li>
<li className={`tab${this.state.log ? " active" : ""}`} onClick={this.handleClick}>Login</li>
</ul>
{this.state.reg ?
<form className="form" id="register" />
<label className="label">Full Name</label>
<input className="input" type="text" onChange={ this.handleRegName } value={ this.state.register.name } required/>
<label className="label">Email</label>
<input className="input" type="email" onChange={ this.handleRegEmail } value={ this.state.register.email } required/>
<label className="label">Password</label>
<input className="input" type="password" onChange={ this.handleRegPass } value={ this.state.register.pass } required/>
<label className="label">Password Confirmation</label>
<input className="input" type="password" onChange={ this.handleRegConf } value={ this.state.register.conf } required/>
<button className="formButton" type="submit">Register</button>
</form>
:
<form className="form" id="login" >
<label className="label">Email</label>
<input className="input" type="email" onChange={ this.handleLogEmail } value={ this.state.login.email } required/>
<label className="label">Password</label>
<input className="input" type="password" onChange={ this.handleLogPass } value={ this.state.login.pass } required/>
<button className="formButton" type="submit">Login</button>
</form>
}
</aside>
This is the structure of my state:
this.state = {
reg: true,
register: {
name: "",
email: "",
pass: "",
conf: ""
},
log: false,
login: {
email: "",
pass: ""
}
}
Here are a couple of my methods (all of the handleRegEmail/handleLogName etc. follow the same structure as handleRegName(e) below):
handleClick(){
let currentReg = this.state.reg;
let currentLog = this.state.log;
this.setState({
reg: !currentReg,
log: !currentLog
})
}
handleRegName(e){
let registerCopy = JSON.parse(JSON.stringify(this.state.register));
registerCopy.name = e.currentTarget.value;
this.setState({
register: registerCopy
});
}
Check where you implement the logic used to validate your forms, the cause of your issue might be there.
Also try adding name attribute to your input elements and use that for validation?
Maybe you use type['...'] for your validation?
Hope any of these help

How to check passwords match in vanilla Vue.js?

I'm new to Vue.js and I'd like to check if passwords are matched.
If they do not match, after the user leaves the confirmation field, the error text Passwords don't match! should appear.
I've seen a couple of solutions which involve using plugins, but I'm wondering what is the idiomatic way to do it using pure vue.js?
https://jsfiddle.net/Babrz/L2md63j7/3/
<div id="app">
<form >
<div class="form-group">
<input type="email" class="form-control" placeholder="Email">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" v-model="password" placeholder="Password">
</div>
<br>
<div class="form-group">
<input type="password" class="form-control" v-model="password2" placeholder="Confirm Passwrd">
</div>
<small v-if="showError">Passwords don't match!</small>
<br>
<div class="form-group">
<input type="text" class="form-control" placeholder="Age">
</div>
<br>
<button type="submit" class="btn login-btn">Register</button>
</form>
</div>
new Vue({
el: "#app",
data: {
email: '',
password: '',
password2: '',
age: 0,
showError: false
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
It sounds like you want to use an onblur event to run a validation on the two password values. A very basic implementation might look like this.
...
<input v-on:blur="validate" type="password" class="form-control" v-model="password2" placeholder="Confirm Passwrd">
...
...
new Vue({
el: "#app",
data: {
email: '',
password: '',
password2: '',
age: 0,
showError: false
},
methods: {
toggle: function(todo){
todo.done = !todo.done
},
validate: function() {
console.log(this.password === this.password2)
}
}
})
...
https://v2.vuejs.org/v2/guide/events.html
You can get a lot of help if you use something like validate.js to validate your passwords too.
http://validatejs.org

Jquery Validation plug-in dependency from Radio buttons not working

I need some inputs to be required only if certain options are checked in another input (radio). In short, if Type 1 documents is chosen, I need type 1 field number to be obligatory. It's easier to visualize through this jsfiddle below:
https://jsfiddle.net/kbhatd51/2/
Could you please help me? Thanks in advance
<form id="registerform" method="post">
<div class="form-group">
<label >Type of Document</label><br>
<input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br>
<input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br>
</div>
<label for="tipop"> Number</label>
<div class="form-group">
<fieldset id="cpf1">
<label for=cpf1>Type 1 No.:</label>
<input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" >
</fieldset>
<fieldset id="cnpj1">
<label for=cnpj1> Type 2 No.:
<input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label>
</fieldset>
</div>
<input name="submit" type="submit" value="Submit!">
</form>
JS validate:
$("#registerform").validate({
rules: {
cpf: {
required: "#fis:checked"
},
cnpj: {
required: "#jur:checked"
}
}
});
The required method needs to return true for the field to be required.
So you can simply pass a function to required which will check if the radio element is checked
required method
required( dependency-callback )
Type: Function()
The function is executed with the element as it's only argument: If it returns true, the element is required.
$("#registerform").validate({
debug: true,
rules: {
cpf: {
required: function(elem) {
return $('#fis').is(":checked")
}
},
cnpj: {
required: function(elem) {
return $('#jur').is(":checked")
}
}
}
});
Check out the -- JSFiddle Example -- here.

Call javascript function on submit form

I am trying to call JavaScript function while submitting the form.
Here is code but while submitting function not called, please suggest something and I want to show error messages using javascript method as well , how can I show error messages in validation using JavaScript.
<form id="register" name="register" onsubmit="validateForm()">
<label for="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" placeholder="Enter Username"> <br><br>
<label for="Password"> Password </label><br>
<input type="password" class="register-control" id="Password" name="Password" placeholder="Enter Password"><br><br>
<label for="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm-Password" name="Confirm-Password" placeholder="Confirm Password" ><br><br>
<label for="email"> Email </label><br>
<input type="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit">Submit</button>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#register").validate({
rules: {
"Username": {
required: true,
},
"Password": {
required: true,
minlength: 5
},
"Confirm-Password": {
required: true,
},
"email": {
required: true,
}
}
});
});
</script>
and here is JavaScript code
function validateForm()
{
var password = document.forms["register"]["Password"].value;
var con-password = document.forms["register"]["Confirm-Password"].value;
if(password != con-password)
{
document.getElementById('password-error').style.visibility='visible';
alert("not matched");
}
alert("matched");
}
This is probably due to a syntax error in your script. When you see errors like that, look into the JavaScript console of your browser.
In this case, con-password is not a valid variable name. What JavaScript sees is:
var con - password ...
i.e. the code says "substract password from con". Try an underscore instead:
var con_password ...
Do not need to do anything extra for password matching, just add equalTo: "#Password" to it as shown in the below example:
$(document).ready(function () {
$("#register").validate({
rules: {
"Username": {
required: true,
},
"Password": {
required: true,
minlength: 5
},
"Confirm-Password": {
required: true,
equalTo: "#Password"
},
"email": {
required: true,
}
},
messages: {
Password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
Confirm-Password: {
required: "Please provide a confirm password",
equalTo: "Please enter the same password as above"
}
},
submitHandler: function(form) {
// Your function call
return false; // return true will submit form
}
});
});
Working example:
<form id="register" name="register" action="" method="post">
<label for="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" placeholder="Enter Username"> <br><br>
<label for="Password"> Password </label><br>
<input type="password" class="register-control" id="Password" name="Password" placeholder="Enter Password"><br><br>
<label for="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm_Password" name="Confirm_Password" placeholder="Confirm Password" ><br><br>
<label for="email"> Email </label><br>
<input type="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit">Submit</button>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#register").validate({
rules: {
"Username": {
required: true,
},
"Password": {
required: true,
minlength: 5
},
"Confirm_Password": {
required: true,
equalTo: "#Password"
},
"email": {
required: true,
}
},
messages: {
Password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
Confirm_Password: {
required: "Please provide a confirm password",
equalTo: "Please enter the same password as above"
}
},
submitHandler: function(form) {
// Your function call
return false; // return true will submit form
}
});
});
</script>
Maybe instead of checking if passwords matches you can add new rule in validation?
something like:
... "Password": {
required: true,
minlength: 5
},
"Confirm-Password": {
required: true,
equalTo: "#Password"} ....
and for messages add:
... messages: {
"Password": "Your message",
}...
and all in all something like this: `
$(document).ready(function () {
$("Your form name").validate({
rules: {
"Username": {
required: true,
},
"Password": {
required: true,
minlength: 5
},
"Confirm-Password": {
required: true,
equalTo: "#Password"
},
"email": {
required: true,
email: true
}
}
messages: {
"Password": "Your message",
"email": "Your Message",
},
submitHandler: function (form) {
form.submit();
}
});
});`
try this. i add onclick event on the submit button to call the function validateForm()
html
<form id="register" name="register">
<label for ="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" placeholder="Enter Username"> <br><br>
<label for ="Password"> Password </label><br>
<input type="password" class="register-control" id="Password" name="Password" placeholder="Enter Password" ><br><br>
<label for ="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm-Password" name="Confirm-Password" placeholder="Confirm Password" ><br><br>
<label for="email" > Email </label><br>
<input type ="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit" onclick="validateForm()">Submit</button>
</form>
this is the validateForm()
<script type="text/javascript">
function validateForm() {
var username = $('#Username'),
password = $('#Password'),
confirm = $('#Confirm-Password'),
email = $('#email');
$('#register').submit(function(ev){
// check if all fields is not empty
if(username.val() === '' || password.val() === '' || confirm.val() === '' || email.val() === '') {
ev.preventDefault(); // prevent form submit
alert('All fields are required.'); //alert message
//check if password and confirm password is equal
} else if(password.val() != confirm.val()){
ev.preventDefault(); // prevent form submit
alert('password did not match.'); //alert message
} else {
return true; // submit form if validation has passed.
}
});
}
</script>
May be you missed - you need to use method="post" in
http://jsfiddle.net/dLbLS/
<form id="register" name="register" method="post" onsubmit="validateForm();" >
<label for ="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username" placeholder="Enter Username"> <br><br>
<label for ="Password"> Password </label><br>
<input type="password" class="register-control" id="Password" name="Password" placeholder="Enter Password" ><br><br>
<label for ="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm-Password" name="Confirm-Password" placeholder="Confirm Password" ><br><br>
<label for="email" > Email </label><br>
<input type ="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit" >Submit</button>
</form>
Use this code
<input type="button" id="close" value="Submit" onClick="window.location = 'validateForm()'">
do one thing i am sending one link please go through that link i have commented my code over there copy and paste it and test it....
How to do validation in JQuery dialog box?
if this answer is correct then please mark it as answer for others....

".errorClass" of jQuery validate works but the class cannot be found by "hasClass()"

Problem
I'm not a programmer and I'm trying to do some programming.
I tried to use jQuery-validate plug-in to control the form input, it works perfectly, Bootstrap can even find the ".text-danger" class and change its' color.
However, the ".hasClass()" method just can't.
I put some "console.log()" functions in the for loops which are used to find this class.
The log messages I received every time are "changed", "hasSmall", "noClass".
Have I made mistakes in the JS code?
Please help me out.
Code
This is within my HTML form:
<div class="form-group">
<label for="username">Username </label>
<input type="text" class="form-control" name="username" id="signUpUserName" />
</div>
<div class="form-group">
<label for="password">Password </label>
<input type="password" class="form-control" name="password" id="signUpPassword" />
</div>
<div class="form-group">
<label for="email">Email </label>
<input type="text" class="form-control" name="email" id="signUpEmail" />
</div>
This is the JavaScript:
errorPlacement: function(error, element) {
var obj = $('[name="'+element.attr('name')+'"]');
obj.siblings('label').append(error);
},
I have changed some values in the valadate.min.js:
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "text-danger", // I've changed this
validClass: "text-success", // this
errorElement: "small", // and this
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
Also, JS:
function changeInputAreaStatus(id) {
$(id).change(function(id) {
console.log('changed');
var errorMessageContainer = $(id).siblings('label');
if(errorMessageContainer.has('small')){
console.log('hasSmall');
if (errorMessageContainer.children('small').hasClass('text-danger')) {
console.log('hasDangerClass');
errorMessageContainer.parent().removeClass('has-error').addClass('has-error');
} else if (errorMessageContainer.children('small').hasClass('text-success')) {
console.log('hasSucessClass');
errorMessageContainer.parent().removeClass('has-error');
} else {
console.log('noClass');
}
}
});
}
changeInputAreaStatus('#signUpUserName');
changeInputAreaStatus('#signUpPassword');
changeInputAreaStatus('#signUpEmail');
You should try something like this :
var textSuccess = errorMessageContainer.find('.text-success');
if(textSuccess != null && textSuccess.length > 0){
console.log('hasSucessClass');
}
it should help you to verify if errorMessageContainer has a text-success class.
Best regards

Categories

Resources