I'm trying to build a simple contact form for the newsletter subscription, the CF has just one input field (email) and the submit button. I used type="email" of HTML5 to check the the email and on the new browsers I get the default validation message:
This doesn't happen when I use older browsers obviously so I used the JS alert in case the user is using the old browsers, but this is not what I'd like.
I would like to get the same message (browser default) on all the browsers.
Here my code:
HTML
<div class="newsletter-wrap-flex margin-top-div">
<div class="newsletter-title">
<span>
NEWSLETTER
</span>
</div>
<div class="newsletter-form">
<form id="newsletter-cf" method="post" action="">
<input id="contact-email" type="email" placeholder="Your email" required/>
<input id="contact-send" class="submit" type="submit" value="Subscribe" />
</form>
<div id="message-sent">Congratulation! Your request has been sent.</div>
</div>
</div>
JS
function checkEmail(inputvalue) {
var pattern = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return pattern.test(inputvalue);
}
$('#newsletter-cf').submit(function () {
var email = document.getElementById("contact-email").value;
if (!checkEmail(email))
{
alert('Email address is invalid');
return false;
}
$("#newsletter-cf").slideUp("slow");
$("#message-sent").slideDown("slow");
return false;
});
I've read there could be some ways like Modernizr but I've never used them before so I don't really know how to start.
Any suggestions?
Related
I'm still learning, so if there's any help, or the answer is really trivial like something I need to put before hand, an explanation of the reason why this is happening would be greatly appreciated!
This has been a problem ever since I have started using it for weekend projects. Whenever I make a button, for example one that I have been trying to use is
<button type="submit" id="btn" onclick="validate()">login</button>
However, when I click on the button, instead of showing me what its supposed to show, it just states this on a gray page.
This page isn’t working
If the problem continues, contact the site owner.
HTTP ERROR 405
HTML
<div class="wrapper">
<form class="box" method="post">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type="submit" id="btn" onclick="validate()">login</button>
</form>
</div>
JS
//I do understand that this is not a good way of setting up a username and password ,since anyone can easily get it. Ive been just doing this as a weekend project, i just want it to show an alert if it works or not
function validate(){
let username = document.getElementById('username');
value;
let password=document.getElementById('password');
value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
I have tried to see if it was a problem with my js, but nothing seems to change, so that is why im starting to suspect that it its the button thats causin the problem
Firstly its not
document.getElementById('password');
value;
its
document.getElementById('password').value;
Secondly, there is no action property present I'll suggest removing the entire form tags
<div class="wrapper">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button type=" submit" id="btn" onclick="validate()">login</button>
</div>
<script>
function validate() {
let username = document.getElementById('username').value;
let password = document.getElementById('password').value;
if (username == 'please' && password == 'work') {
alert('finally');
} else {
alert("NOOOO")
}
}
</script>
on your for, you are using attibute method="post" which has alternative of method="get" which being sent using URLs you are using method="post" which has a missing attribute action="/action_page.php" that will process you're page.
Like this
<form class="box" action="/action_page.php" method="post">
since you don't have action attribute, and has method="post", the post is being sent to the same page you are sending and without receiving it properly like in php.
$username = $_POST['username'];
If you still want to continue using javascript at test it, remove at post method, and remove the type="submit" on your button as it behaves on submitting if you just want to test using javascript.
Here is your final script.
HTML
<form class="box">
<h3>login</h3>
<div class="username">
<input type="text" placeholder="enter username" id="username" name="usernmame" value="">
</div>
<div class="password">
<input type="password" placeholder="enter password" id="password"">
</div>
<button id="btn" onclick="validate()">login</button>
</form>
</div>
JS
function validate(){
let username = document.getElementById('username').value;
let password=document.getElementById('password').value;
if(username =='please' && password == 'work')
{
alert('finally');
} else{
alert("NOOOO")
}
}
First post here so please be gentle. I'm trying to self learn how to write a responsive website for a local club. Is there any way of checking that two password fields are identical and error accordingly using the bootstrap 4 method of form validation? I can do it server side but since I am doing a fair amount of client side form validation, it would be nice if I could check that the passwords were the same before submitting the form.
<form class="container" id="form-validation" method="post" action="./register.php" novalidate>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation1">Username</label>
<input type="text" class="form-control" name="username" id="validation1" placeholder="Username" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation2">Password</label>
<input type="password" class="form-control" name="pwd1" id="validation2" placeholder="Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<label for="validation3">Confirm Password</label>
<input type="password" class="form-control" name="pwd2" id="validation3" placeholder="Re-enter Password" required pattern="^[_a-zA-Z0-9\-]{5,15}$">
<div class="invalid-feedback">
Must be alpha-numeric, dash or underscore, between 5 & 15 characters and match original Password
</div>
</div>
</div>
<div class="row">
<div class="col-md-10 mb-3">
<button class="btn btn-success" type="submit" value="Send" name="registerbtn">Register</button>
</div>
</div>
</form>
(function() {
"use strict";
window.addEventListener("load", function() {
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
}, false);
}());
Using this should work.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You can achieve this validation through the JavaScript constraint validation API, it's a customError, which you can set prior to form submission.
I'll provide the example for BootStrap4 and assume jQuery as an optional but common BootStrap dependency to abbreviate $("#pw1").val()
The HTML
<form>
<div class="form-group">
<label for="pw1">Password</label>
<input type="password" class="form-control"
id="pw1" placeholder="Password"
required minLength=8>
</div>
<div class="form-group">
<label for="pw2">Repeat Password</label>
<input type="password" class="form-control"
id="pw2" placeholder="Password" aria-describedby="pwHelp"
required minLength=6
oninput="validate_pw2(this)">
<small id="pwHelp" class="form-text text-muted">Please repeat your password</small>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
The Script
<script>
function validate_pw2(pw2) {
if (pw2.value !== $("#pw1").val()) {
pw2.setCustomValidity("Duplicate passwords do not match");
} else {
pw2.setCustomValidity(""); // is valid
}
}
</script>
The important parts are the oninput in #pw2, which attempts to validate every time the value its changed. Then the setCustomValidity call provides the user message displayed when invalid, the empty string is used when it is now valid.
You can put a check to verify the password values are the same and abort the submission if they're not.
var form = document.getElementById("form-validation");
form.addEventListener("submit", function(event) {
if ( document.getElementById("validation2").value != document.getElementById("validation3").value ) {
alert("Password mismatch");
event.preventDefault();
event.stopPropagation();
}
else if (form.checkValidity() == false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
You would just change the alert window to show error text to your user. Here is an example to see how it would look: https://jsfiddle.net/aq9Laaew/55184/
Another suggestion would be to use something like jQuery so that the syntax is less cumbersome to deal with. But that's up to you.
From your code checkValidity() will check only the validity of the form HTML5 constraint (required, format, pattern, min, max), but there is no constraint for verify password. In reality this is like comparing if the content of 2 fields is the same. Also if you want to cancel the form submission, you also needs to return false; at the end. Normally HTML5 will not submit a form that has validation errors.
In you case I will suggest make a validation while you are typing on the validation field, and disable the submit button until the passwords match.
document.getElementById('validation3').addEventListener('keyup',function(e){
if(this.value !== document.getElementById('validation2').value){
document.getElementById('validation4').disabled=true;
this.classList.replace('pass','nopass');
}else{
document.getElementById('validation4').disabled=false;
this.classList.replace('nopass','pass');
}
}
You will need to assign an id='validation4' to the submit button. To make visual changes you could create a CSS rules to handle this ('pass','nopass').
I have a bootstrap 3 form and I am using validator to validate forms.
I have succesfully implemented basic validations for sign-in forms and now I am implementing validation of change password form.
The form is as follows:
<form id="changepassword-form" role="form" data-toggle="validator" class="form-quote" action="/changepasswordpost" method="POST">
<input name="changepassword-id" type="hidden" value="{{ id }}"/>
<input name="changepassword-token" type="hidden" value="{{ token }}"/>
<div class="form-group row">
<div class="form-field col-md-12 form-m-bttm">
<input name="changepassword-password" type="password" placeholder="Nueva contraseña *" class="form-control required">
</div>
</div>
<div class="form-group row">
<div class="form-field col-md-12 form-m-bttm">
<input name="changepassword-password2" type="password" placeholder="Repita la nueva contraseña *" class="form-control required">
</div>
</div>
<button id="changepassword-submit" type="submit" class="btn btn-primary">Cambiar contraseña</button>
</form>
I see in the documentation that custom validation can be used so I have written the following validation intended to be used in the second password field:
custom: {
passwordmatch: function($el) {
var matchValue = $('#changepassworde-password').value()
if ($el.val() !== matchValue) {
return "Passwords do not match"
}
}
}
But I do not know where or how can I define this custom validation. I understand that once defined I should just apply data-passwordmatch='' to second password field.
You should use html attributes as it is mentioned in the validator
data-match="#inputToMatch" to ensure two fields match, e.g. password confirmations
Validation rules are specified on form inputs via the following standard HTML5 attributes:
type="email"
type="url"
type="number", with additional constraints via max, min and step attributes
pattern="Reg(ular )?Exp(ression)?" (for input types of text, search, tel, url or email)
required
As well as the following non-standard attributes:
data-match="#inputToMatch" to ensure two fields match, e.g. password confirmations
data-minlength="5" to enforce a minimum amount of characters
data-remote="/path/to/remote/validator" to make an AJAX request to determine if the field is valid or not. Be sure to give the input a name attribute, as the request will be sent to /path/to/remote/validator?<name>=<value>. The remote endpoint should return a 200 OK if the field is valid, and a 4xx otherwise. Here's a reference server implementation using Express.
I want to make this compatible for browsers which do not support HTML5 validation. Basically, all I am trying to do is give the basic error by default from the browser with HTML5 and also add a class of error to each input, label and parent div for each field that has an error which I will have some additional CSS effects such as red text/border. What is happening is I get the default error message from the browser but no error classes are added to my input, label or div. If I remove HTML5 required from one of the fields and fill out the rest of the form it will then run my function and add the error classes. Below you will see my form and my jQuery function to add the error classes.
What I think is happening is when HTML5 finds an error it is not running my submit function which would add the error classes. I have figured I could trigger the invalid bind function for each input and add the error classes but I then don't think I would have any validation if the browser didn't support HTML5 validation.
jQuery portion:
$('#contact_us_form').submit(function() {
var error_count = 0;
$('#contact_us_form div').each(function() {
$(this).removeClass('error');
});
$('#contact_us_form input').each(function() {
$(this).removeClass('error');
});
$('#contact_us_form label').each(function() {
$(this).removeClass('error');
});
if ($('#fname').val() == '') {
error_count++;
$('#fname').parent('div').addClass("error");
$('#fname').addClass("error");
$('label[for="fname"]').addClass("error");
}
if ($('#lname').val() == '') {
error_count++;
$('#lname').parent('div').addClass("error");
$('#lname').addClass("error");
$('label[for="lname"]').addClass("error");
}
if ($('#email').val() == '') {
error_count++;
$('#email').parent('div').addClass("error");
$('#email').addClass("error");
$('label[for="email"]').addClass("error");
} else if (!isValidEmailAddress( $('#email').val() ) ){
error_count++;
$('#email').parent('div').addClass("error");
$('#email').addClass("error");
$('label[for="email"]').addClass("error");
}
if ($('#phone').val() == '') {
error_count++;
$('#phone').parent('div').addClass("error");
$('#phone').addClass("error");
$('label[for="phone"]').addClass("error");
} else if (!isPhone($('#phone').val())) {
error_count++;
$('#phone').parent('div').addClass("error");
$('#phone').addClass("error");
$('label[for="phone"]').addClass("error");
}
if ($('#message').val() == '') {
error_count++;
$('#message').parent('div').addClass("error");
$('#message').addClass("error");
$('label[for="message"]').addClass("error");
}
if (error_count == 0) {
submitFormWithAjax();
}
return false;
});
HTML form:
<form class="form form_careers" action="#" id="contact_us_form">
<fieldset>
<legend>Contact Information</legend>
<div class="field-name-first">
<label for="fname" class="inlined">First Name</label>
<input accesskey="f" class="input-text" id="fname" name="fname" required tabindex="1" type="text" value="" />
</div>
<div class="field-name-last">
<label for="lname" class="inlined">Last Name</label>
<input accesskey="l" class="input-text" id="lname" required tabindex="2" type="text" />
</div>
<div class="field-email-primary">
<label for="email" class="inlined">Email</label>
<input accesskey="e" class="input-text" id="email" required tabindex="3" type="email" />
</div>
<div class="field-phone-primary">
<label for="phone" class="inlined">Phone</label>
<input accesskey="p" class="input-text" id="phone" required tabindex="4" type="tel" />
</div>
<div class="field-message-comments">
<label for="message" class="inlined">Message/Comments</label>
<textarea accesskey="m" class="" id="message" required tabindex="5"></textarea>
</div>
<!--input class="cta_button cta_primary" tabindex="7" type="submit" value="Contact Us" /-->
<button class="cta_button cta_primary" tabindex="6">Contact Us</button>
</fieldset>
</form>
You could use a framework like modernizr to detect if the document supports the invalid event. While initializing your app, check to see if invalid is a supported event. If so, bind to invalid, if not bind to submit. It's a pretty robust framework (customizable and relatively small) for detecting support of various features.
This question might be of some help as well:
How to bind to the submit event when HTML5 validation is used?
What you are looking for is a polyfill for HTML5 validation.
This will basically, use javascript validation in cases where the clients browser is lacking. Polyfills are implemented in cases where a browser doesn't support the feature, which leads toward a natural, and optimized web browsing experience for the user.
This is a good resource for HTML5 form polyfills:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#web-forms
On polyfills:
http://en.wikipedia.org/wiki/Polyfill
I am pretty sure I am missing something very obvious but I am trying to validate my one of the textbox with required condition and I am using Jquery validator for that. My code looks like below:
var validator = $("#ForgotPassword").validate({
rules: {
EmailAddress: { required: true }
},
messages: {
EmailAddress: {
required: "Email address is required."
}
}
});
My DOm is like something below:
<form id = "ForgotPassword" class="ui-helper-hidden" title="Forgot Password" action="" method="GET">
<p>Please enter the email address you registered with. We’ll send you an email with a password reset link.</p>
<div class="inputwrapper _100">
<label for="Email">Email</label>
<input type="text" id="EmailAddress" name="Email" data-bind ="value : ForgotPasswordEmailAddress"/>
<span id="EmailAddress_Error" class="ui-helper-hidden errorMessage" ></span>
</div>
</form>
But when I put a watch on my validator object on the run time, I do not see any error. Is is because I am looking at the wrong place or my binding are not right?
Try this please or paste rest of your validation code:
For validation plugin you need to have name - EmailAddress in this case:
Hope it help the cause :)
<form id = "ForgotPassword" class="ui-helper-hidden" title="Forgot Password" action="" method="GET">
<p>Please enter the email address you registered with. We’ll send you an email with a password reset link.</p>
<div class="inputwrapper _100">
<label for="Email">Email</label>
<input type="text" id="EmailAddress" name="EmailAddress" class="EmailAddress" data-bind ="value : ForgotPasswordEmailAddress"/>
<span id="EmailAddress_Error" class="ui-helper-hidden errorMessage" ></span>
</div>
</form>
I think the problem is with the name in rules and messages. You should be using Email as the rule and message not EmailAddress because thats the name attribute on the control