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
Related
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?
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.
This is my code :
<form>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope fa-10x"></i></span>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" required="required">
</div>
<br/>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-10x"></i></span>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" required="required">
</div>
<br/>
<button type="button" class="btn btn-default">Submit</button>
</form>
required="required" is working if I change button type = "submit", but I want to use button type = "button" only, as I want to submit the form using AJAX. How do I use required field using button type = "button" ?
Why don't you try to use standard type button "submit" and assign to event of the form "submit" handler, where first call event.preventDefault(), to prevent form sending, and then call AJAX.
Understand the concept, button do not accept any user value in it, so you cannot put required field validation on it. Instead you can put required validation on email, password field. On button click these fields are checked whether they have some value in it or not. If not the error is displayed.
This can be achieve by using the jquery validation like:
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5
},
"email": {
required: true,
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
}
}
});
Working fildle
Another Fiddle
You can't put validation for CallToAction fields/buttons..instead you can validate input fields where user must fill out some data.
Also there is no necessity to assign required value for required field..you can simply write <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" required/>
When submit a form we can check validation. But if you want to use
type='button' then please call a javascript function to check validation.
for example:
$('#btn').on('click', function() {
$("#form1").valid();
});
jsFiddle Demo
check out bootstrap validations in detail here (version 3.2 and later) : http://bootstrapvalidator.votintsev.ru
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.
in my webapp i have the need to allow users to enter unlimited email addresses in a form i have this working nicely its allowing multiple input fields to be added and is validating them perfectly thanks to the below question i found
How to validate array of inputs using validate plugin jquery
i have read the question and made the changes to my code and can confirm in console that its validating each input field and not allowing the form to be submitted
my problem is it only shows the "please enter your email" for one of the input fields. for example if i had 2 fields and enter an email in the first when i submit the form the "please enter your email" for the second input shows under the first input field
what possible methods are there to make it show for all
this is my JS so far
var validator = $(".webapp_auth_login_validation").validate({
rules: {"email[]": "required"},
messages: {"email[]": "Please enter you email"}
});
$('.webapp_js_cu_email_new').click(function(){
$('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label> Remove <input type="text" name="email[]" class="form-control required"></div>');
});
$('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
this is the html on the page
<div class="row webapp_js_cu_email_container">
<div class="col-md-4 form-group">
<label>Email Address: <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
<input type="text" name="email[]" class="form-control required">
</div>
http://jsfiddle.net/gL1k4efa/6/
Here is a workaround to your issue.
Explanation The var validator = ... is used to provide a template to the inputs with email[] names.
They are then selected with their email-input class and provided rules with an email type and required callbacks in the createValidation() function - and a custom error message.
The function is called a first time and whenever you add an email input to the form.
var emailCounter = 1;
var validator = $(".webapp_auth_login_validation").validate({
rules: {
"email[]": "required"
},
messages: {
"email[]": "Please enter you email"
}
});
var createValidation = function() {
$(".email-input").each(function() {
$(this).rules('remove');
$(this).rules('add', {
email: true,
required: true,
messages: {
email: "Not a valid email.",
required: "Please enter an email adress."
}
});
});
}
$('.webapp_js_cu_email_new').click(function() {
$('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label> Remove <input id="email[' + (emailCounter) + ']" type="text" name="email[' + (emailCounter) + ']" class="form-control required email-input"></div>');
// Increment input counter
++emailCounter;
// Create validation
createValidation();
});
$('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e) {
e.preventDefault();
$(this).parent('div').remove();
});
// Kick validation
$(document).ready(function() {
createValidation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form class="webapp_auth_login_validation">
<div class="row webapp_js_cu_email_container">
<div class="col-md-4 form-group">
<label>Email Address: <span class="text-danger">*</span>
</label> Add
<input type="text" name="email[0]" class="form-control required email-input">
</div>
</div>
<input type="submit">
</form>
Your JS code is right, the problem is with your HTML code. You said have a list of emails, then you need and array, but you have to set indexes to that array or the DOM wont be well formed and the validator will fail.
Try to set and index for each input field.
<div class="col-md-4 form-group">
<label>Email Address: <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
<input type="text" name="email[0]" class="form-control required">
</div>
And here adding the right index:
$('.webapp_js_cu_email_new').click(function(){
$('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label> Remove <input type="text" name="email[+obtainIndex()+]" class="form-control required"></div>');
});
You can try below code it validate each field for required validation and also for valid email address check for each field and in this what i did in each element add index using count variable and i have create one function which add validation rules for email and required filed both after every time add new filed. function name for that is callToEnhanceValidate try below code it will solve your problem for both required and valid email address validation also.
<form class="webapp_auth_login_validation">
<div class="row webapp_js_cu_email_container">
<div class="col-md-4 form-group">
<label>Email Address: <span class="text-danger">*</span></label> <a href="javascript:void(0);" class="webapp_js_cu_email_new" > Add </a>
<input type="text" name="email[]" class="form-control required emailValidate">
</div>
</div>
<input type="submit">
</form>
<script type= text/javascript>
var count = 1;
var validator = $(".webapp_auth_login_validation").validate({
rules: {"email[]": "required"},
messages: {"email[]": "Please enter you email"}
});
var callToEnhanceValidate=function(){
$(".emailValidate").each(function(){
$(this).rules('remove');
$(this).rules('add', {
required: true,
email : true,
minlength:2,
messages: {
required: "Please enter you email"
},
});
})
}
$('.webapp_js_cu_email_new').click(function(){
count++;
$('.webapp_js_cu_email_container').append('<div class="col-md-4 form-group"><label>Additional Email: <span class="text-danger">*</span></label> Remove <input type="text" name="email['+count+']" class="form-control required emailValidate"></div>');
callToEnhanceValidate();
});
$('.webapp_js_cu_email_container').on('click', '.webapp_js_cu_email_remove', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
</script>
in this i have also added new class "emailValidate" in each dynamic generated filed and also for first field so now this code validate for both required and email validation both validation you can also try below fiddle link working code
fiddle link for working demo of required and email validate both validation