Populating error message with field name in Parsley js - javascript

I couldn't find anything in the Parsley docs or in Google.
Is there an easy way to set an attribute in input and populate the error message with custom message.
For example:
<label>First name
<input type="text" required/>
</label>
with give a standard error "This value is required."
But it would be nice to have something like
<label>First name
<input type="text" required data-parsley-field-name="Last name"/>
</label>
with error like "Last name is required"
Or as an option, just grad string from<label>.
I know that I can set custom messages, but you have to do it on each input.

This will your job
<form method="post" id="myForm">
<input type="text" name="phone" class="form" data-err="last name" value="" class="required" data-parsley-required="" />
<input type="text" name="phone" class="form" data-err="First name" value="" class="required" data-parsley-required="" />
<input type="submit" value="Go">
$(document).ready(function() {
$("#myForm").parsley();
$.listen('parsley:field:error', function(){
var i = 0;
$("#myForm .form").each(function(k,e){
var field = $(e).data("err");
$(e).next("ul").find("li:eq("+i+")").html(field+" is required");
});
});
});
here is working fiddle JsFiddle

Related

addEventListener with a form element

I'm new with Javascript and I'm learning by myself. I have a problem with a form on my page. I just want to test with a simple javascript code that I can manipulate my input "type=submit" by adding a function to it to console.log a string when the form is submitted (I watched it on a video and I wanted to do it by myself).
Here is my code:
(function() {
"use strict";
document.getElementById('enviar').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
and this is my HTML code:
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
The problem that I'm having here is that is not working at all.. my ID element is selected properly but I don't know what is wrong with my code. I created a variable and console my ID selected to see if I was getting the right element from the DOM and I'm getting in the console the right input element. please if someone knows why is not working.
plus: On my text input field I have a regular expression but I'm not getting the output I want.. the goal is that the user has to write at least two names (First and Last), so when they write just one it will be incorrect.. the problem that I'm having with this regular expression if when someone writes more than two names (First, Middle and Last) I DON'T want to make that an incorrect answer because technically is correct. So I need to make a better regular expression to get that result (when the user writes two or more names, not just two) but I don't know too much about Regular Expressions.
You are getting the element with the id enviar which is the submit button element. You need to be querying based on the form's element id which is escribenos. Try running the snippet below and you can see that it has the expected outcome.
(function() {
"use strict";
document.getElementById('escribenos').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>

Disable form fields on input into a group of other fields

I have the below form and would like to use jQuery to do the following:
1/ Disable the fields 'filter_from' and 'filter_to' if any character is entered into any one or more of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'.
2/ Re-enable the fields 'filter_from' and 'filter_to' only if there is no input in any of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'. That is, all 4 of these fields are empty.
I have the below code which works for point 1 - It disables the 2 fields when any of the other fields have data entered.
It does not work as required for point 2 - It currently re-enables the 2 fields if any one of the other fields is cleared. It should only re-enable the 2 fields when all of the other fields are cleared.
The fields 'filter_com' and 'filter_employer' should be ignored. They are only mentioned here to explain that not all of the fields on the form are to be used to disable the other 2 fields, just selected fields.
<form>
<input name="filter_from" type="text" autocomplete="off">
<input name="filter_to" type="text" autocomplete="off">
<input name="filter_loan_id" type="text" autocomplete="off">
<input name="filter_fname" type="text" autocomplete="off">
<input name="filter_lname" type="text" autocomplete="off">
<input name="filter_postcode" type="text" autocomplete="off">
<input name="filter_com" type="text" autocomplete="off">
<input name="filter_employer" type="text" autocomplete="off">
</form>
$(document).ready(function() {
$('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').change(function() {
if ($(this).val() != '') {
$('input[name=filter_from]').prop('disabled', true);
$('input[name=filter_to]').prop('disabled', true);
} else {
$('input[name=filter_from]').prop('disabled', false);
$('input[name=filter_to]').prop('disabled', false);
}
});
});
Try concatenating the values of all the relevant inputs and use that for checking
$(document).ready(function() {
var disableable = $('input[name=filter_from], input[name=filter_to]'),
valuable = $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').on('input change', function() {
var combinedValue = valuable.get().map(function(element) {
return element.value;
}).join('');
disableable.prop('disabled', combinedValue !== '');
});
valuable.trigger('change');
});
input:disabled{background:#ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
filter_from<input name="filter_from" type="text" autocomplete="off"><br> filter_to
<input name="filter_to" type="text" autocomplete="off"><br> filter_loan_id
<input name="filter_loan_id" type="text" autocomplete="off"><br> filter_fname
<input name="filter_fname" type="text" autocomplete="off"><br> filter_lname
<input name="filter_lname" type="text" autocomplete="off"><br> filter_postcode
<input name="filter_postcode" type="text" autocomplete="off"><br> filter_com
<input name="filter_com" type="text" autocomplete="off"><br> filter_employer
<input name="filter_employer" type="text" autocomplete="off">
</form>

What is the best way to do form validation before submitting

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.

How to make the user enter either of the 2 fields

<input type="text" name="firstname" placeholder=" Enter First Name" required/><input type="hidden" name="search" value="true" >
<input type="text" name="lastname" placeholder="Enter Last Name" /><input type="hidden" name="search" value="true" >
I have got these 2 text boxes and I am using these text boxes for searching users on a webpage.
I want the users can search using both these text boxes.
I have written the query for that but I am facing a problem, if user writes anything in either of the text boxes then it should not show any error on the front end but if user leaves both text fields empty then an error should be generated and I want to do it on the design page.
I don't want to write a validation code for that.
I have tried required field but it does not work in my case as either of the 2 text boxes should be input with data.
If you want to do validation in UI, please follow the below steps
1) Provide id's to both the input fields, which are used to validate the fields
<input type="text" id="firstname" name="firstname" placeholder=" Enter First Name" required/><input type="hidden" name="search" value="true" >
<input type="text" id="lastname" name="lastname" placeholder="Enter Last Name" /><input type="hidden" name="search" value="true" >
2) Using javascript you can valiate as below
function validate() {
if(document.getElementById("firstname").value.trim() != "" && document.getElementById("lastname").value.trim() != "" ) {
// show alert saying required input fields.
} else {
// do the submit action
}
}
3) Call the validate function on submit of the form.
Using Jquery/java script you can do client side validation..
Your HTML
<input type="text" id="first" name="firstname" placeholder=" Enter First Name" /><input type="hidden" name="search" value="true" >
<input type="text" id ="last" name="lastname" placeholder="Enter Last Name" /><input type="hidden" name="search" value="true" >
<input type="button" id="button1" value="check"/>
Validation
$("#button1").click(function()
{
$first=$("#first").val();
$sec=$("#last").val();
if(($first=="")&&($sec==""))
{
alert("Please enter any");
}
});

JQuery - Duplicate Field Input Text In Real Time

I'm trying to figure out how to copy a users text input in one form field to another. Specifically, when someone fills in their email address in the contact form, it will be duplicated in the mailing list form.
Both these forms are using ajax so there's no concerns about the input text being lost on submit.
This is the code I have:
<div id="contact_form">
<form name="contact" method="post" action="">
<input type="text" name="name" id="name" size="30" value="Name" class="text-input" />
<label class="error" for="name" id="name_error">Please enter your name.</label>
<br />
<input type="text" name="email" id="email" size="30" value="Email" class="text-input" />
<label class="error" for="email" id="email_error">I need your email.</label>
<br />
<textarea rows="10" cols="30" type="textarea" name="message" id="message" value="Message" class="text-input" ></textarea>
<label class="error" for="message" id="message_error">A message is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit" value="Send" />
</form>
</div>
<div id="details">
<p>some details here, not sure what yet</p>
</div>
<div id="mail_list">
<input type="text" id="mail" value="Your email" name="mail_list" /><input type="submit" name="submit" class="button" id="submit" value="Send" />
</div>
I found this in the Jquery documentation, but couldn't get it to work:
$("#email").optionCopyTo("#mail");
Thanks!
You said you want it in real time. I assume that means while the user is typing, the value should be replicated for each keystroke.
If that's right, try this:
var mail = document.getElementById("mail");
$("#email").keyup(function() {
mail.value = this.value;
});
Or if you want more jQuery:
var $mail = $("#mail");
$("#email").keyup(function() {
$mail.val( this.value );
});
This will update for each keyup event.
I'd probably add a redundant blur event in case there's an autocomplete in the field.
$("#email").blur(function() {
$mail.val( this.value );
});
Since all your fields have unique ids, this is quite straight forward:
$(function() { // <== Doc Ready
$("#email").change(function() { // When the email is changed
$('#mail').val(this.value); // copy it over to the mail
});
});
Try it out with this jsFiddle
.change()
.val()
Is $("#mail") another input box ? It doesn't appear in your HTML (Edit: well it does now, but didn't at first :)
$("#mail").val($("#email").val()) should do what you want.
use keyup and change both.
$("#boxx").on('keypress change', function(event) {
var data=$(this).val();
$("div").text(data);
});
here is the example
http://jsfiddle.net/6HmxM/785/
you can simply do this
$('#mail').text($('#email').val())

Categories