please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>
I've made a form with required fields and custom error messages/validation, which all display/work correctly, however if the error is corrected, the form still cannot be submitted. This was working before I added the inline oninvalid checks. Not sure what I'm doing wrong.
Code:
<form role="form" method="post" action="contact-form.php">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="this.setCustomValidity ('Please enter your name.')" />
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="this.setCustomValidity ('Please enter your message.')"></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />
</form>
<script>
var email = document.querySelector( "#email" );
function setErrorMessage() {
if ( email.validity.valueMissing ) {
email.setCustomValidity( "Please enter your email address." );
} else if ( email.validity.typeMismatch ) {
email.setCustomValidity( "Please enter a valid email address." );
}
};
setErrorMessage();
email.addEventListener( "change", setErrorMessage );
</script>
JSFiddle: http://jsfiddle.net/44Lrgmjc/
Any help would be greatly appreciated!
Thanks.
I adjusted your javascript and added (key) a validate email function. here is a fiddle
function validate{
function email(){
if(form.email.value == "") {
alert("Please enter your email");
form.email.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if(!re.test(form.email.value)) {
alert("Invalid email address");
form.email.focus();
return false;
}
// validation was successful
return true;
}
function name(){
If(form.name.value == "") {
alert("Please enter your name");
form.name.focus();
return false;
}
// validation was successful
return true;
}
function msg{
if(form.message.value == "") {
alert("Please enter your message");
form.message.focus();
return false;
}
// validation fails if the input doesn't match our regular expression
if(!re.test(form.message.value)) {
alert("Invalid message content");
form.message.focus();
return false;
}
// validation was successful
return true;}}
</script>
<script>
function validateEmail()
{
var emailID = document.form.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form.email.focus() ;
return false;
}
return( true );
}
<form role="form" method="post" action="contact-form.php" onsubmit="return validate(this);">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="alert ('Please enter your name.')"/>
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required oninvalid="alert ('Please enter a valid email.')"/>
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="alert ('Please enter your message.')" ></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl"/>
</form>
Reference
I have a project in which I have to add a registration form and I want to to validate that the password and confirm fields are equal without clicking the register button.
If password and confirm password field will not match, then I also want to put an error message at side of confirm password field and disable registration button.
following is my html code..
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" /></label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
</label>
<label>
<input type="submit" name="submit" value="registration" />
</label>
Is there any way to do this?
We will be looking at two approaches to achieve this. With and without using jQuery.
1. Using jQuery
You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password field changes. Thanks #kdjernigan for pointing that out
In this way, when you type in the field you will know if the password is same or not:
$('#password, #confirm_password').on('keyup', function () {
if ($('#password').val() == $('#confirm_password').val()) {
$('#message').html('Matching').css('color', 'green');
} else
$('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
<input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/
2. Without using jQuery
We will use the onkeyup event of javascript on both the fields to achieve the same effect.
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'green';
document.getElementById('message').innerHTML = 'matching';
} else {
document.getElementById('message').style.color = 'red';
document.getElementById('message').innerHTML = 'not matching';
}
}
<label>password :
<input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onkeyup='check();' />
<span id='message'></span>
</label>
and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/
Using Native setCustomValidity
Compare the password/confirm-password input values on their change event and setCustomValidity accordingly:
function onChange() {
const password = document.querySelector('input[name=password]');
const confirm = document.querySelector('input[name=confirm]');
if (confirm.value === password.value) {
confirm.setCustomValidity('');
} else {
confirm.setCustomValidity('Passwords do not match');
}
}
<form>
<label>Password: <input name="password" type="password" onChange="onChange()" /> </label><br />
<label>Confirm : <input name="confirm" type="password" onChange="onChange()" /> </label><br />
<input type="submit" />
</form>
If you don't want use jQuery:
function check_pass() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('submit').disabled = false;
} else {
document.getElementById('submit').disabled = true;
}
}
<input type="password" name="password" id="password" onchange='check_pass();'/>
<input type="password" name="confirm_password" id="confirm_password" onchange='check_pass();'/>
<input type="submit" name="submit" value="registration" id="submit" disabled/>
Solution Using jQuery
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<style>
#form label{float:left; width:140px;}
#error_msg{color:red; font-weight:bold;}
</style>
<script>
$(document).ready(function(){
var $submitBtn = $("#form input[type='submit']");
var $passwordBox = $("#password");
var $confirmBox = $("#confirm_password");
var $errorMsg = $('<span id="error_msg">Passwords do not match.</span>');
// This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
$submitBtn.removeAttr("disabled");
function checkMatchingPasswords(){
if($confirmBox.val() != "" && $passwordBox.val != ""){
if( $confirmBox.val() != $passwordBox.val() ){
$submitBtn.attr("disabled", "disabled");
$errorMsg.insertAfter($confirmBox);
}
}
}
function resetPasswordError(){
$submitBtn.removeAttr("disabled");
var $errorCont = $("#error_msg");
if($errorCont.length > 0){
$errorCont.remove();
}
}
$("#confirm_password, #password")
.on("keydown", function(e){
/* only check when the tab or enter keys are pressed
* to prevent the method from being called needlessly */
if(e.keyCode == 13 || e.keyCode == 9) {
checkMatchingPasswords();
}
})
.on("blur", function(){
// also check when the element looses focus (clicks somewhere else)
checkMatchingPasswords();
})
.on("focus", function(){
// reset the error message when they go to make a change
resetPasswordError();
})
});
</script>
And update your form accordingly:
<form id="form" name="form" method="post" action="registration.php">
<label for="username">Username : </label>
<input name="username" id="username" type="text" /></label><br/>
<label for="password">Password :</label>
<input name="password" id="password" type="password" /><br/>
<label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" id="confirm_password" /><br/>
<input type="submit" name="submit" value="registration" />
</form>
This will do precisely what you asked for:
validate that the password and confirm fields are equal without clicking the register button
If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button
It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.
Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.
function check() {
if(document.getElementById('password').value ===
document.getElementById('confirm_password').value) {
document.getElementById('message').innerHTML = "match";
} else {
document.getElementById('message').innerHTML = "no match";
}
}
<label>password :
<input name="password" id="password" type="password" />
</label>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" onchange="check()"/>
<span id='message'></span>
HTML CODE
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
JS CODE
function checkPass(){
var pass = document.getElementById("password").value;
var rpass = document.getElementById("rpassword").value;
if(pass != rpass){
document.getElementById("submit").disabled = true;
$('.missmatch').html("Entered Password is not matching!! Try Again");
}else{
$('.missmatch').html("");
document.getElementById("submit").disabled = false;
}
}
try using jquery like this
$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});
also add this line in head of html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
$('input[type=submit]').on('click', validate);
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("valid");
}
else {
$("#validate-status").text("invalid");
}
}
Logic is to check on keyup if the value in both fields match or not.
Working fiddle: http://jsfiddle.net/dbwMY/
More details here: Checking password match while typing
<form id="form" name="form" method="post" action="registration.php" onsubmit="return check()">
....
</form>
<script>
$("#form").submit(function(){
if($("#password").val()!=$("#confirm_password").val())
{
alert("password should be same");
return false;
}
})
</script>
hope it may help you
Try this one ;
CSS
#indicator{
width:20px;
height:20px;
display:block;
border-radius:10px;
}
.green{
background-color:green;
display:block;
}
.red{
background-color:red;
display:block;
}
HTML
<form id="form" name="form" method="post" action="registration.php">
<label >username :
<input name="username" id="username" type="text" /></label> <br>
<label >password :
<input name="password" id="password" type="password" id="password" /></label> <br>
<label>confirm password:
<input type="password" name="confirm_password" id="confirm_password" /><span id="indicator"></span> <br>
</label>
<label>
<input type="submit" name="submit" id="regbtn" value="registration" />
</label>
</form>
JQuery
$('#confirm_password').keyup(function(){
var pass = $('#password').val();
var cpass = $('#confirm_password').val();
if(pass!=cpass){
$('#indicator').attr({class:'red'});
$('#regbtn').attr({disabled:true});
}
else{
$('#indicator').attr({class:'green'});
$('#regbtn').attr({disabled:false});
}
});
WITHOUT clicking the button you will have to listen to the change event of the input fields
var confirmField = document.getElementById("confirm_password");
var passwordField = document.getElementById("password");
function checkPasswordMatch(){
var status = document.getElementById("password_status");
var submit = document.getElementById("submit");
status.innerHTML = "";
submit.removeAttribute("disabled");
if(confirmField.value === "")
return;
if(passwordField.value === confirmField.value)
return;
status.innerHTML = "Passwords don't match";
submit.setAttribute("disabled", "disabled");
}
passWordField.addEventListener("change", function(event){
checkPasswordMatch();
});
confirmField.addEventListener("change", function(event){
checkPasswordMatch();
});
then add the status element to your html:
<p id="password_status"></p>
and set the submit button id to submit
... id="submit" />
hope this helps you
$box = $('input[name=showPassword]');
$box.focus(function(){
if ($(this).is(':checked')) {
$('input[name=pswd]').attr('type', 'password');
} else {
$('input[name=pswd]').attr('type', 'text');
}
})
You can check confirm password by only simple javascript
html
<input type="password" name="password" required>
<input type="password" name="confirmpassword" onkeypress="register()" required>
<div id="checkconfirm"></div>
and in javascript
function register() {
var password= document.getElementById('password').value ;
var confirm= document.getElementById('confirmpassword').value;
if (confirm!=password){
var field = document.getElementById("checkconfirm")
field.innerHTML = "not match";
}
}
Also you can use onkeyup instead of onkeypress.
The code proposed by #Chandrahasa Rai
works almost perfectly good, with one exception!
When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :)
Now everything should be working fine!
#Chandrahasa Rai,
HTML code:
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
#my modification:
<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
I think this example is good to check https://codepen.io/diegoleme/pen/surIK
I can quote code here
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
and
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
I made a contact form for my website and I want to make validations. This is the HTML:
<form name="contact" method="post" action="Contact.php" onsubmit="return validateForm()" >
<span class="formtext"> name:</span> <input id="nameinput" type="text" name="name" /><br />
<span class="formtext"> email:</span> <input id="mailinput" type="text" name="email" /><br />
<span class="formtext"> message:</span><br /> <textarea id="messageinput" type="text" name="message"> </textarea> <br />
<input id="submitinput" name="submit" type="submit" value="שלח"/>
</form>
This is the JS:
// Contact Form //
function validateForm()
{
var x=document.forms["contact"]["name"].value;
var y=document.forms["contact"]["email"].value;
var atpos=y.indexOf("#");
var dotpos=y.lastIndexOf(".");
var z=document.forms["contact"]["email"].value;
if (x==null || x=="" || y==null || y=="" || z=="" || z==null)
{
alert("Please fill all the details");
return false;
}
else
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=y.length)
{
alert ("Please fill a valid email address");
return false;
}
}
The problem has something to do with the variable 'z'. When I fill the form and send it, I get the "Please fill all the details" alert, even though I did fill the textarea. I know it's the 'z' because if I remove both the variable and the part inside the 'if' that has something to do with var 'z', the problem is solved- but then there is no validation.
The z also handles the email input instead of the message textarea
Try replacing
var z=document.forms["contact"]["email"].value;
by
var z=document.forms["contact"]["message"].value;
I am providing a validation feature on a form for passwords. I need to be able to implement a few validation rules and have them all checked on submit. Now to me the code is sound but I think they may be some logic error in my code that I'm too tired to notice (too the coffee machine!)
Here's the JavaScript:
<script type="text/javascript">
<!--
function validate(registerForm)
registerForm.onsubmit=function()
{
var pw1 = document.forms["register"]["password1"].value;
var pw2 = document.forms["register"]["password2"].value;
//Check values are present in both fields
if(pw1 == '' || pw2 == '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 != pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
//Accept passwords
{
alert("Password accepted!");
return true;
}
}
}
-->
</script>
And the HTML Form to go with it:
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" value="Register" />
</form>
<script type="text/javascript">
<!--
new validate(document.forms['register']);
-->
</script>
Any ideas of lovely StackOverflow community? The exact problem is that it won't check for spaces in passwords or whether two passwords entered are the same. It successfully checks that there is at least something in both password fields.
Thanks Dan
This line:
else if(document.forms["register"]["password1"].value.indexOf(invalid) > - 1)
invalid is not defined and I suspect this will cause the problems you're facing.
Made changes to your code got it working http://jsbin.com/igonec/edit#preview
ERRORS
Use of var pw1 = document.forms["register"]["password1"]. It was causing errors
Missing else.
Use of invalid instead of " ".
Wrong use of brackets.
I omitted your errors and made the solution more elegant.
Javascipt
function validate()
{
var pw1 = document.getElementById("password1").value;
var pw2 = document.getElementById("password2").value;
//Check values are present in both fields
if(pw1 ==='' || pw2 === '')
{
alert("Please enter your password twice.");
return false;
}
//Check there no spaces
else if(document.getElementById("password1").value.indexOf(" ") > - 1)
{
alert("Spaces are not allowed in passwords!");
return false;
}
//Check passwords are the same
else
{
if(pw1 !== pw2)
{
alert("The passwords you entered were not the same. Please try again!");
return false;
}
else
{
alert("Password accepted!");
return true;
}
}
}
HTML
<form id="register">
<label for="username">Username</label>
<input type="text" class="input_text" name="username" id="name" placeholder="e.g. AberLibrary01" />
<br />
<label for="password">Password</label>
<input type="text" class="input_text" name="password1" id="password1" placeholder="e.g. aber01" />
<br />
<label for="re-enterpassword">Re-enter password</label>
<input type="text" class="input_text" name="password2" id="password2" placeholder="e.g. aber01" />
<input type="submit" class="button" onclick="validate()" value="Register" />
</form>