I am busy using a jquery script that validates users password in real time. I would like to adjust it only accept a password if it has a letter, number and special character in it.
jQuery("#ValidEmail").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a valid Email ID"
});
jQuery("#ValidPassword").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\#[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Please enter a special character"
});
I am stumped on how to do this as it does not accept normaly regex experesions that I can find off the web eg
(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
Any idea on how to solve this. Im bashing my head in here
As far as I can tell from the documentation, what you're using is not a supported syntax for adding validation methods to jQuery validate:
/* INCORRECT: */
jQuery("#element").validate({
expression: "if (/*...*/) return true; else return false;",
message: "Please enter a valid Email ID"
});
If you need custom validation rules, that is done with addMethod():
/* CORRECT: */
jQuery.validator.addMethod("methodname", function(value, element) {
// return true if value is valid
}, "message");
jQuery("#myform").validate({
rules: {
elementname: "methodname",
/* ... */
}
});
Your custom "email" validator is unnecessary; jQuery validate has its own. Here is an example of your password validator in action:
jQuery.validator.addMethod(
"myPasswordMethod",
function(value, element) {
// This is your regex, I have not looked closely at it to see if it is sensible
return value.match(/^[^\W][a-zA-Z0-9\_\-\.]+([a-zA-Z0-9\_\-\.]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/);
},
"Please enter a valid password"
);
$("#myForm").validate({
rules: {
pwd: "myPasswordMethod",
mail: "email" // don't reinvent the wheel; there is a built-in email validation method
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myForm">
<label for="mail">Email</label>
<input id="mail" name="mail"><br>
<label for="pwd">Password</label>
<input id="pwd" name="pwd"><br>
</form>
As discussed exhaustively in comments, clientside password validation (or any other clientside validation) is insufficient on its own. Validate on the client for the user's convenience; re-validate on the server to prevent user shenanigans or to handle disabled clientside scripting.
Related
This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 9 months ago.
Referring to this issue:
How can I set a minimum length for a field with jQuery?,
<form id="new_invitation" class="new_invitation" method="post" data-remote="true" action="/invitations" accept-charset="UTF-8">
<div id="invitation_form_recipients">
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_0"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_1"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_2"><br>
<input type="text" value="" name="invitation[recipients][]" id="invitation_recipients_3"><br>
</div>
<input type="submit" value="Send invitation" name="commit">
</form>
What would the code be for settting a minimum length for a field with jQuery?
$('#new_invitation').submit(function(event) {
if ($('#invitation_form_recipients input').filter(function() {
return $(this).val();
}).length == 0) {
// All the fields are empty
// Show error message here
// This blocks the form from submitting
event.preventDefault();
}
});
How can I validate that every field input have a valid email address with jQuery? In the above code?
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}
This regex can help you to check your email-address according to all the criteria which gmail.com used.
var re = /^\w+([-+.'][^\s]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var emailFormat = re.test($("#email").val()); // This return result in Boolean type
if (emailFormat) {}
Email: {
group: '.col-sm-3',
enabled: false,
validators: {
//emailAddress: {
// message: 'Email not Valid'
//},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'Email not Valid'
},
}
},
This : /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case
gmail.#gmail.com
gmail#.gmail.com
Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex
I found this Solution from this URL:
Regex Solution link
/(?:((?:[\w-]+(?:\.[\w-]+)*)#(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g
This :
var email = /^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
function mailValidation(val) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}
I am trying to give a textfield a dual function. So, if you type, say, 12345, into it, it finds the relevant data. But if you type an email-address, or essentially anything with an XXX#XXX.XXX format, I want the password-field and button to appear. I've been trying to use regex, but for some reason it does not work, and everything is recognised as an email, so even 12345 opens the login-things. Can you help me? I've tried getting the gist into the snippets.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (iDCode = mail) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>
user mail.test() with proper regex like so
let mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mail.test(iDCode)){
alert("Valid email is required")
}
You can try this version, it's based on the w3resource.
function imgMain() {
var iDCode = document.getElementById("IDQuery").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (iDCode.match(mailformat)) {
console.log("this is a mail");
document.getElementById("passwordDiv").style.display = "block";
document.getElementById("loginbuttonDiv").style.display = "block";
document.getElementById("SeeSlide").style.display = "none";
} else {
console.log("this is not a mail")
}
}
<div id="QueryField">
<input type="text" id="IDQuery" placeholder="ID Kode">
<div style="display: none" id=passwordDiv><input type="password" id="passwordfield"><br></div>
<div style="display: none" id=loginbuttonDiv><button id="login" onclick="login()">log ind</button><br></div>
<button id="SeeSlide" onclick="imgMain()">Se Slide</button><br>
<br><br><br><br>
</div>
In your if statement you have if (iDCode = mail).
This re-assigns the value of mail to the variable iDCode. So the if effectively becomes if(mail) which is always true, because RegEx objects are truthy.
You should instead be checking if the input matches the regex, using either mail.test(iDCode) or iDCode.match(mail)
Few different ways. You can send an email to that address and check whether it bounces back or you can use PHP (I doubt you want to do this since your question is JavaScript) and send an email and then have them confirm it on the web address. Honestly, PHP is the best way to do this but since you're using JS you can try this from https://www.w3resource.com/javascript/form/email-validation.php:
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)) {
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
This works because we are checking all the invalid characters that are in an email address. If the input field contains any of those characters, its invalid.
Try Googling the answer. There are lots of information:
https://www.google.com/search?rlz=1C1GCEB_enUS865US865&ei=bn9dXuefDanJ0PEPofOHyAg&q=javacsript+check+email+address&oq=javacsript+check+email+address&gs_l=psy-ab.3..0i71l8.2549.3358..3533...0.2..0.0.0.......12....1..gws-wiz.........23%3A11-12j24%3A11-2.1hEMZpGGmWs&ved=0ahUKEwjnjr7N4vznAhWpJDQIHaH5AYkQ4dUDCAw&uact=5&safe=active&ssui=on
You can try using the .validate function. It works really great for checking login forms.
The function could look like the following:
$("#IDQuery").validate({
rules: {
email:
{required: true, email: true},
password:
{required: true}
},
messages: {
email:
{required: 'Please enter a E-mail',
email: 'Please enter a valid E-mail'},
password:{required: 'Please enter a password'}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>
So in my registration form I have this field:
<div class="form-group">
<label for="RegisterModel_Password">Password</label>
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password" class="form-control"
required="required" minlength="8"/>
</div>
As you see, I'm using jQuery validation attributes to ensure that the password includes at least 8 characters. So, I want to check if password contains uppercase and number, if not, field is not valid. I downloaded additional method for jQuery Validation plugin named "pattern" and added her in head tag.
I tried to do this as follows but it didn't worked.
$("#formRegister").validate({
rules: {
RegisterModel_Password: {
pattern: /^[a-zA-Z][0-9]/
}
}
});
I assume that the pattern is wrong, but I'm not sure whether the use is correct.
Thank you for your help.
Chains of regular expressions are too hard for me ( I have never tried to learn them lol ). So here is my solution:
jQuery.validator.addMethod("passwordCheck",
function(value, element, param) {
if (this.optional(element)) {
return true;
} else if (!/[A-Z]/.test(value)) {
return false;
} else if (!/[a-z]/.test(value)) {
return false;
} else if (!/[0-9]/.test(value)) {
return false;
}
return true;
},
"error msg here");
And simply I use it like a attribute:
<input type="password" id="RegisterModel_Password"
name="RegisterModel.Password"
class="form-control"
required="required" minlength="8"
passwordCheck="passwordCheck"/>
Thanks for your answers.
You can add your custom validation using $.validator.addMethod() like:
$.validator.addMethod("validation_name", function(value) {
// at least 1 number and at least 1 character
[^\w\d]*(([0-9]+.*[A-Za-z]+.*)|[A-Za-z]+.*([0-9]+.*))
});
I searched and can't figure out how to validate the new reCaptcha, before form submit, along with the validate function of jQuery validation Plugin.
My intent:
$.validator.addMethod('reCaptchaMethod', function (value, element, param) {
if (grecaptcha.getResponse() == ''){
return false;
} else {
// I would like also to check server side if the recaptcha response is good
return true
}
}, 'You must complete the antispam verification');
$("#form").validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
reCaptcha: {
reCaptchaMethod: true
}
},
messages: {
name: "Please fill your name",
email: "Please use a valid email address"
},
submitHandler : function () {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
In a few words: I would like to check server-side, with the remote method, if the user has passed the recaptcha validation BEFORE submitting the form, along with other rules of validation.
I'm able to check the recaptcha AFTER submission (on sendmail.php), but it would be nicer to have the recaptcha validation response along with other fields validation.
The main reason is for a better user experience, having all fields checked at once.
I've managed to achieve this, moving the check inside the submitHandler:
submitHandler : function () {
if (grecaptcha.getResponse() == ''){
// if error I post a message in a div
$( '#reCaptchaError' ).html( '<p>Please verify youare human</p>' );
} else {
$.ajax({
type : "POST",
url : "sendmail.php",
data : $('#form').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
}
But I don't like this approach, for 2 reasons:
It is just checking if the recaptcha has been filled, not if it's valid, and
User feels like it is a 2 step verification.
In this answer they say it can be done rendering the Recaptcha on a callback, to specify a function call on a successful CAPTCHA response.
I tried to implement that, but I've not been able to use this solution within a rule of the validate() function.
I know this question is a bit dated but I was having the same problem and just found the solution.
You can do this by adding a hidden field next to the reCaptcha div, like:
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
then in your javascript:
$("#form").validate({
ignore: ".ignore",
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
hiddenRecaptcha: {
required: function () {
if (grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},(...rest of your code)
NOTICE THAT YOU MUST HAVE the ignore: ".ignore" in your code because jquery.validate ignores hidden fields by default, not validating them.
If you want to remove the error message on reCapcha validate add a data-callback to the reCapcha element
<div class="g-recaptcha" data-sitekey="{YOUR-SITE-KEY-HERE}" data-callback="recaptchaCallback"></div>
And then in your js file add
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
You can also prevent the form submit in the submitHandler
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 6
},
password: {
required: true,
},
},
submitHandler: function(form) {
if (grecaptcha.getResponse()) {
form.submit();
} else {
alert('Please confirm captcha to proceed')
}
}
});
I've found your solution to be interesting (#FabioG).
But, I've modified it for use a bit by myself and I'm willing to share the code for others to use.
I was working on an interactive form, that validated as you completed steps.
It was used for ordering food. Ergo, the form required verification and activation of the register button and it is using the latest reCaptcha to date (5/12/2016).
Also, this code handles expired reCaptcha, server-side verification via ajax (though not included - if someone needs it to feel free to comment on my answer and I'll edit it accordingly).
Let's get started.
The HTML code:
<form id="registerForm" method="get" action="">
<fieldset class="step-1">
<h4>Step One:</h4>
<span class="clock">Register under one minute!</span>
<label for="email-register" class="label">E-mail*</label>
<input id="email-register" name="email-register" type="email" value="" autocomplete="off"/>
<label for="password-register" class="label">Password*</label>
<input id="password-register" name="password-register" type="password" value="" autocomplete="off"/>
<div class="g-recaptcha" data-sitekey="6LeS4O8SAAAAALWqAVWnlcB6TDeIjDDAqoWuoyo9" data-callback="recaptchaCallback" data-expired-callback="recaptchaExpired" style="margin-top: 3rem;"></div>
<input id="hidden-grecaptcha" name="hidden-grecaptcha" type="text" style="opacity: 0; position: absolute; top: 0; left: 0; height: 1px; width: 1px;"/>
</div>
</fieldset>
<fieldset class="step-2">
<h4>Step two:</h4>
<span class="notice">All fields with a sign are required!*</span>
<label for="first-name" class="label">First Name*</label>
<input name="first-name" id="first-name" type="text" value="" />
<label for="last-name" class="label">Last Name*</label>
<input name="last-name" id="last-name" type="text" value="" />
<label for="address" class="label">Address*</label>
<input name="address" id="address" type="text" value=""/>
<label for="entrance" class="label">Entrance</label>
<input name="entrance" id="entrance" type="text" value=""/>
<label for="apartment-number" class="label">Apartment #</label>
<input name="apartment-number" id="apartment-number" type="text" value="" />
<label for="inter-phone" class="label">Interphone</label>
<input name="inter-phone" id="inter-phone" type="text" value=""/>
<label for="telephone" class="label">Mobile Number*</label>
<input name="telephone" id="telephone" type="text" value="" />
<label for="special-instructions" class="label">Special Instructions</label>
<textarea name="special-instructions" id="special-instructions"></textarea>
<div>
</fieldset>
<button class="button-register" disabled>Register</button>
</form>
So as you can see, the button for submission (".button-register") is initially disabled.
You can only enable it by filling the mandatory (*) fields.
Please, keep in mind that I didn't include any CSS. The form is on a bare minimum and is just for educational purposes.
Few things that differ from #FabioG, the answer is:
There is no need to hide the element or use the ".ignore". I've hidden it with inline CSS.
There is a response callback for successful reCaptcha and expired reCaptcha.
So, if your reCaptcha expires while filling out the form it will make it invalid and the button will be disabled again.
As well, the form uses an input field (the hidden input field) to pass the information onto AJAX(PHP later on) and verify it server-side (It is a potential security risk, I covered it more at the end of the text).
Let's move on to JavaScript/jQuery.
JavaScript/jQuery:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function recaptchaCallback() {
var response = grecaptcha.getResponse(),
$button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val(response);
console.log(jQuery("#registerForm").valid());
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function recaptchaExpired() {
var $button = jQuery(".button-register");
jQuery("#hidden-grecaptcha").val("");
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}
function submitRegister() {
//ajax stuff
}
(function ($, root, undefined) {
$(function () {
'use strict';
jQuery("#registerForm").find("input").on("keyup", debounce(function() {
var $button = jQuery(".button-register");
if (jQuery("#registerForm").valid()) {
$button.attr("disabled", false);
}
else {
$button.attr("disabled", "disabled");
}
}, 1000));
jQuery("#registerForm").validate({
rules: {
"email-register": {
required: true,
email: true
},
"password-register": {
required: true,
minlength: "6"
},
"first-name": "required",
"last-name": "required",
address: "required",
telephone: "required",
"hidden-grecaptcha": {
required: true,
minlength: "255"
}
},
messages: {
"email-register": "Enter valid e-mail address",
"password-register": {
required: "Enter valid password",
minlength: "Password must be bigger then 6 chars!"
},
"first-name": "Required!",
"last-name": "Required!",
address: "Required!",
telephone: "Required!"
},
submitHandler: submitRegister
});
});
})(jQuery, this);
As you can see here, there are a few functions: recaptchaCallback() and recaptchaExpired().
recaptchaCallback() that is embeded via the data attribute data-callback, uses the grecaptcha.getResponse() to see if the reCaptcha is validated, if so it enters the token to the hidden input field and asks for re-validation via the jQuery("#registerForm).validate();.
However, if the reCaptcha expires in the meanwhile it will use the assigned function in the "data-expired-callback", to remove the token from the input field and ask for re-validation again which will fail because the field is empty. This is achieved with the function recaptchaExpired().
Later in the code, you can see that we added a jQuery keyup function, to check for re-validation and see if the user has passed on the required information to the input fields. If the information and the field validate successfully the keyup function will enable the Register button.
Also, I've used a debounce script (tnx, David Walsh) on keyup. So it doesn't cause browser lag. Since, there would be a lot of typing.
But, keep in mind if a user decides to circumvent the reCaptcha he can always just enter the "255" character long string to the input field. But, I've gone a step further and made an AJAX verification server-side to confirm the reCaptcha. Though, I haven't included it in the answer.
I think this code is a marginal improvement on the previous answer. If you have any questions or need the AJAX/PHP code feel free to comment. I'll supply it when I can.
Heres the codepen as well: reCaptcha with jQuery.validation
You can find all the information regarding the reCatpcha data-attributes and functions in their API here: reCaptcha API
Hope it helped someone!
Regards,
I struggled with this one today and ended up going with:
<form onsubmit="return $(this).valid() && grecaptcha.getResponse() != ''">
Which just feels like the simplest way to do it. Someone is bound to complain about putting js inline like that but I'm ok with it.