Issue
I am having a problem creating a custom validator for the Parsley.js plugin. What I'm trying to do is test a value vs a regex. Specifically, I'm trying to validate that a password value includes at least one uppercase and one lowercase letter. The validation code throws an error, but does not return true when the condition has been satisfied.
HTML
<form name="Form" id="signupform" method="post" action="#" data-parsley-validate data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden">
<label for="password1">New Password <span class="req">*</span></label>
<input name="password" id="password1" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspannewpassinput" data-parsley-required-message="Please enter your new password." data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" data-parsley-required/>
<span class="errorspannewpassinput"></span>
<label for="confirm_password1">Confirm Password <span class="req">* </span></label>
<input name="Password_2" id="password2" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspanconfirmnewpassinput" data-parsley-required-message="Please re-enter your new password." data-parsley-equalto="#password1" data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" data-parsley-required />
<span class="errorspanconfirmnewpassinput"></span>
<input type="submit" name="submitinfo" id="submitsignup" data-theme="b" style="width:100%;" alt="Sign Up Now" value="Submit Account Request" />
</form>
jQuery
$(function() {
// Set variables
var pmixedCase = 'Y';
var mixedCase = $('.mixedcase');
var passwordField = $('#password1, #password2');
var passwordFieldErrors = $('.errorspannewpassinput, .errorspanconfirmnewpassinput');
// Assemble list of visible password requirements
// Mixed Case
if (pmixedCase === 'Y') {
mixedCase.show();
} else {
mixedCase.hide();
}
// Custom Validators
window.Parsley.addValidator('mixedcase', {
requirementType: 'regexp',
validateString: function(value, requirement) {
return requirement.test(value);
},
messages: {
en: 'Your password must contain at least (1) lowercase and (1) uppercase letter.'
}
});
});
I've included a JSFiddle below.
Fiddle
The issue you're facing is that your JsFiddle is using Parsley 2.1.2 whereas the documentation is already updated to Parsley 2.2.0.
If you look at the Javascript console you'll see an error:
Uncaught TypeError: window.Parsley.addValidator is not a function
Which means that the version you're using is not yet updated (the previous versions used window.ParsleyValidator.addValidator). So, if you simply update Parsley.js to the correct version your code will work. See this fiddle.
However, there's a simpler way to accomplish what you need (that is, without a custom validator). You can use the built-in Pattern (data-parsley-pattern). For example:
<form name="Form" id="signupform" method="post" data-parsley-validate data-parsley-excluded="input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden">
<label for="password1">New Password <span class="req">*</span></label>
<input name="password" id="password1" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspannewpassinput" data-parsley-required-message="Please enter your new password." data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter." data-parsley-required />
<span class="errorspannewpassinput"></span>
<label for="confirm_password1">Confirm Password <span class="req">*</span></label>
<input name="Password_2" id="password2" type="password" class="password" data-parsley-minlength="1" data-parsley-errors-container=".errorspanconfirmnewpassinput" data-parsley-required-message="Please re-enter your new password." data-parsley-equalto="#password1" data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" data-parsley-required data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter."/>
<span class="errorspanconfirmnewpassinput"></span>
<input type="submit" name="submitinfo" id="submitsignup" data-theme="b" style="width:100%;" alt="Sign Up Now" value="Submit Account Request" />
</form>
What I've changed:
Replaced data-parsley-mixedcase="^(?=.*[a-z])(?=.*[A-Z]).*$" for data-parsley-pattern="(?=.*[a-z])(?=.*[A-Z]).*" on both inputs.
As per Marc-André Lafortune's comment I removed the ^ at the start and the $ at the end, because the patterns are now anchored.
Added data-parsley-pattern-message="Your password must contain at least (1) lowercase and (1) uppercase letter." on both inputs.
JsFiddle available here.
Related
Please some one suggest me on,
What is the best way to do form validation before submitting?
Actual scenario is like, i have a button called save,so when user press save button.
I need to validate the data and pass the flow to server to store the data in the tables.
Instead of doing form data validation in server side, is there any possible way to check those in client side itself
<form>
<header>
<h1>Testing </h1>
</header>
<p>
Receipt number:
<input type="text" id="grn" class="tb1" onkeypress="return isNumber(event)" /> Type
<select name="evalu" id="evalu">
<option value="electrical">Electrical</option>
<option value="mechanical">Mechanical</option>
</select>
cad
<select name="cd" id="cd">
<option value="unit1">xv</option>
<option value="unit2">ed</option>
</select>
<input type="button" id="find" value="Find" class="button0" />
<br>
<br> Report No
<input type="text" name="irepno" id="irepno" class="tb1" maxlength="8" /> date
<input type="text" name="idt" id="idt" class="tb1" value="<%= new SimpleDateFormat(" dd-MM-yyyy ").format(new java.util.Date())%>">
<input type="button" id="search" value="Search" class="button0" />
<br></br>
<input type="button" value="Save the record" id="saverecord" class="button0">
</p>
</form>
Javascript itself is developed with an intention to add client side processing of data and validations.
The best way depends on the situation where you are applying and also the
javascript technologies.
If you are not using any specific client side technologies or frameworks for example angularjs or emberjs etc.
You can try using jquery validation plugin
which is avialable ate
https://jqueryvalidation.org/
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
label,
input {
display: block;
}
input{
margin-bottom:15px;
}
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="John" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Doe" />
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
There are many ways to validate a form. I prefer validating a form using HTML elements which is a quick way to check the input details.
Here is a code snippet I used to validate details entered by the client in a simple form.
<fieldset>
<legend>Enter Your Details</legend>
<p>
<label for="fave"> Mobile:
<input maxlength="10" autofocus="on" autocomplete="on" name="mobile" placeholder="Mobile number"/>
</label>
</p>
<p>
<label for="name"> Name:
<input maxlength="30" pattern="^.* .*$" required size="15" name="name" placeholder="Your name"/>
</label>
</p>
<p>
<label for="password"> Password:
<input type="password" required name="password" placeholder="Min 6 characters"/>
</label>
</p>
<p>
<label for="email">
Email: <input type="email" pattern=".*#mydomain.com$" placeholder="user#domain.com" id="email" name="email"/>
</label>
</p>
<p>
<label for="tel">
Tel: <input type="tel" placeholder="(XXX)-XXX-XXXX" id="tel" name="tel"/>
</label>
</p>
<p>
<label for="url">
Your homepage: <input type="url" id="url" name="url"/>
</label>
</p>
</fieldset>
Few elements like
type, maxlength, pattern, required, size
are used for validating a form in client side.
I like the book The Definitive Guide to HTML5, where you can learn to validate a form using front-end development.
Hope this solves your problem.
On form submit, write javascript or jquery script to validate and pass form values to your servlets.
you can use this jquery plugin too.
There are some great validation libraries out there. One I like in particular is jQuery.validate.js as it is well documented and easy to use.
If you would prefer to write your own, a good place to start would be this W3Schools article on Javascript form validation
I suggest you to options, you can choose yourself:
1) Write your validate code inside the function when you click saverecord button.
2) Validate input field (in your case I guess that "Receipt number" and "Report No" is only number), you can write function to handle onkeypress ( or onchange) event to validate which typing from users.
This question already has answers here:
Strip white spaces on input
(4 answers)
Closed 6 years ago.
I have a signup form that requires an email. when a user uses an android device and enters their email, if they have used the device before android auto suggests their email. If the user selects the auto suggestion it ads a trailing blank space at the end. then when the user goes to signup the system says invalid email because of the blank space. users dont always see the blank space. How can I remove the trailing blank space automatically.
I already have a piece of js that uses the check this function to compare email address entered for repeat email.
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail');
var emailRepeat = document.getElementById('eMail_repeat');
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
var email = document.getElementById("eMail").value.trim();
var repeat = document.getElementById("eMail_repeat").value.trim();
demo can be found here. Enter whitespace after the email inputs to check.
edit: Clearer demo can be found here, with sample addresses provided, and highlighting the differences between using .trim() and not using it.
you can use $.trim() function here:
<form name="account_reg_form" method="post" action="{$rlBase}{if $config.mod_rewrite}{$pageInfo.Path}.html{else}?page={$pageInfo.Path}{/if}" enctype="multipart/form-data">
<div style="margin-top:10px;">
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
</div>
<div style="margin-top:10px;">
<input size="45" class="wauto" id="eMail_repeat" type="text" name="email_addr_repeat" title="Repeat your email address" placeholder="Repeat your email address" required oninput="check(this)" />
</div>
<input type="submit" value="{$lang.next_step}" />
</form>
<script>
function check() {
var email = document.getElementById('eMail').value.trim();
var emailRepeat = document.getElementById('eMail_repeat').value.trim();
if (email.value != emailRepeat.value) {
emailRepeat.setCustomValidity('The two email addresses must match.');
} else {
// input is valid -- reset the error message
emailRepeat.setCustomValidity('');
}
}
</script>
<input style="text-transform:lowercase;" id="eMail" size="45" class="wauto" type="text" name="profile[mail]" {if $smarty.post.profile.mail}value="{$smarty.post.profile.mail}"{/if} required oninput="check(this)" />
You can use Javascript's String.replace with this regex /\s+$/. It would replace the text with empty string.
string.replace(/\s+$/, '')
Example:
var testString = " test string ";
console.log(testString.replace(/\s+$/, ''); // logs: " test string"
DEMO
Note: We could have used the trim() function directly but it removes leading as well as trailing spaces whereas we want only trailing. trimLeft and trimRight are neither standerdized nor implemented in all browsers.
Just use the Jquery snippet below so that, even if you select an email with spaces, it will be trimmed using the input bind event.
It even will not allow spaces.
$(function(){
$('#eMail').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
$('#eMail_repeat').bind('change', function(){
$(this).val(function(_, v){
return v.replace(/\s+/g, '');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="email" id="eMail"/>
<input type="email" id="eMail_repeat"/>
Pls run the code snippet, paste any email with spaces directly, and it automatically trim's the spaces.
Here is a fiddle
I'm try to validate email and names and what not. I'm using a jquery plugin to try and validate my form. But the thing is that the form does not even go to the javascript, it seems to just reset. Could someone help me?
Here's the html:
<form action method="post" id="register" name="register" class="well form-horizontal">
<label>Username:</label><input type="text" name="username" id="username" />
<label>Email:</label><input type="text" name="email" id="email" />
<label>Password:</label><input type="password" name="password1" id="password1" />
<label>Repeat Password</label><input type="password" name="password2" id="password2" />
<input type="submit" class="btn" value="Submit" />
</form>
Here's my javascript (it's from the jquery plugin):
function myOnComplete () {
alert("does this even work?");
return false;
}
$(document).ready(function() {
$("#register").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Please enter a username.",
"required,email,Please enter your email address.",
"valid_email,email,Please enter a valid email address.",
"required,password1,Please enter a password.",
"custom_alpha,password1,xxxDDD,The first three characters must be numbers, the last three must be letters."
]
});
return true;
});
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
I want to check that two passwords are the same using Dojo.
Here is the HTML I have:
<form id="form" action="." dojoType="dijit.form.Form" />
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
invalidMessage="This password doesn't match your first password" /></p>
<div dojoType="dijit.form.Button" onClick="onSave">Save</div>
</form>
Here is the JavaScript I have so far:
var onSave = function() {
if(dijit.byId('form').validate()) { alert('Good form'); }
else { alert('Bad form'); }
}
Thanks for your help. I could do this in pure JavaScript, but I'm trying to find the Dojo way of doing it.
This will get you a lot closer
setting intermediateChanges=false keeps the validator running at every keystroke.
the validation dijit's constraint object is passed to its validator. Use this to pass in the other password entry
dijit.form.Form automatically calls isValid() on all its child dijits when it's submitted, and cancels submittion if they don't all validate. I though the invalid ones would get their error message, but they don't. That's left as an exercise for the reader ;-)
the validation function:
function confirmPassword(value, constraints)
{
var isValid = false;
if(constraints && constraints.other) {
var otherInput = dijit.byId(constraints.other);
if(otherInput) {
var otherValue = otherInput.value;
console.log("%s == %s ?", value, otherValue);
isValid = (value == otherValue);
}
}
return isValid;
}
function onsubmit()
{
var p1 = dijit.byId('password1').value;
var p2 = dijit.byId('password2').value;
return p1 == p2;
}
and the input objects:
<p>Password: <input type="password"
name="password1"
id="password1"
dojoType="dijit.form.ValidationTextBox"
required="true"
intermediateChanges=false
invalidMessage="Please type a password" /></p>
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
constraints="{'other': 'password1'}"
validator=confirmPassword
intermediateChanges=false
invalidMessage="This password doesn't match your first password" /></p>
Even easier, use the pre-written Dojox widget, dojox.form.PasswordValidator.
http://docs.dojocampus.org/dojox/form/PasswordValidator
It does everything you want straight out of the box!
I've solved it!
This page on the Dojo forum was helpful.
I changed the HTML for the confirm password to:
<p>Confirm: <input type="password"
name="password2"
id="password2"
dojoType="dijit.form.ValidationTextBox"
required="true"
validator="return theSame(this, dijit.byId('password1'));"
invalidMessage="This password doesn't match your first password" /></p>
The only difference is the added validator parameter.
And I created the following JavaScript function:
function(dojoTxt1, dojoTxt2) {
return dojoTxt1.getValue() == dojoTxt2.getValue();
}
I think you can also use the validator parameter to create regular expressions to test against, but the documentation isn't very clear.