Rails - Setting custom validation messages for input field(front-end) - javascript

I need to set custom messages for text field in a form for pattern mismatch and empty field.
I have done all validation in backend but I also need to do this in front-end.
text_field:
<%= f.text_field :id_number, pattern: "[0-9]*", required: true, oninvalid: "this.setCustomValidity('Only numbers allowed')", oninput: "setCustomValidity('')" %>
The above one works fine on invalid pattern but, it also displays the same message 'Only numbers allowed' if the field is empty.
How can I set different messages for different errors that works in all type of browsers?
Anyone please help..
Thank you..

I am adding my answer - how to use the wonderful jquery.validate library for client side validation.
I am using version 1.13.1
Here it goes..
Download the library and place it in app/assets/javascripts/jqueryValidation/dist folder which includes additional-methods.min.js and jquery.validate.min.js.
Add the library in your asset pipeline so that its available globally.
//= require jqueryValidation/dist/jquery.validate
//= require jqueryValidation/dist/additional-methods
start using the library on the form in your _form.html.erb.
<%= form_for(#new,:html=>{:id=>"newForm") do |f |%>
//input fields with text/number/textarea etc
<%end%>
initialize the script and validate the form input fields.
$("form#new_form").validate({
//use this to ignore autocomplete fields present,if any
ignore: "",
//set rules for input elements using name attribute
rules: {
"new_form[address]": "required",
"new_form[tag]": "required",
"new_form[title]": {
required: true,
minlength: 3,
maxlength: 100
},
"new_form[contact_email]": {
required: true,
email: true,
minlength: 5,
maxlength: 100
},
"new_form_photos[avatar][]": {
required: true,
extension: "jpeg|jpg|png|gif"
},
//use this to show custom dedicated placeholder message everytime validation fails...just like dynamic alert
errorPlacement: function(error, element) {
$("#show_error").html("<span class='text-danger' >Fields marked with * are required</span>");
},
//use this callback to get which field is currently failing validation and then add more custom logic if needed
//for eg: you want to update the color of name label if validation fails.
//validator.errorList contains an array of objects, where each object has properties "element" and "message". element is the actual HTML Input.
invalidHandler: function(e,validator) {
//use the key value pair to get => id=new_form_title, to identify your input field
for (var i=0;i<validator.errorList.length;i++){
console.log(validator.errorList[i].element.attributes['id'].value);
if ( validator.errorList[0].element.attributes['id'].value == "new_form_tag"){
//handle tag input field here by adding css/alert/focus etc
}
}
}
});//validation ends
Similarly, we have submitHandler: function(form) {},onkeyup: function (element, event) {)
Hope it helps. :)

Giving you a very simple Example using Jquery for client-side validation. Try it:
Your form like, app/views/users/_form.html.erb
<%= form_for(#message=Message.new, :html => {:id => 'contact-form'}) do |f| %>
<div class="form-group">
<label for="phoneNo">Phone Number:</label>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<span class="glyphicon glyphicon-phone"> </span>
</span>
<%= f.text_field :contact, class: 'form-control' %>
</div>
</div>
In js file: app/assets/javascritps/users.js
$(document).on('ready page:load', function(){
$('#contact-form').validate({
rules:{
"message[contact]": {
required: true,
regex: /^[0-9]{10}$/
}
},
messages:{
"message[contact]":{
required: "Enter your contact number",
regex: "Enter valid contact number"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("regex", function(value, element, regexpr) {
return regexpr.test(value);
}, "Enter valid number");
});

For client side validation you need to require jquery.validate.min(get it from https://jqueryvalidation.org/) in your js file. Then You can use form id to validate. Suppose your form id is #sliderForm and you want to validate textfield
<input id="slider_banner_title" name="slider_banner[title]" placeholder="Enter title" size="30" title="title" type="text" maxlength="255">
Then do like this:
$('#sliderForm').validate
rules:
"slider_banner[title]":
required: true
maxlength: 44
messages:
"slider_banner[title]":
required: "Title can't be blank"
maxlength: "Maximum 44 characters are allowed"
here slider_banner[title]" is name in input field.

I think the best way to define this in the model class. For an example if this input field is associated to an object related to the User model then, you define the following validations in the model,
validates :id_number, presence: {message: 'Id number required'}
validates :id_number, numericality: {message: 'Id number invalid data'}
Let me know if this works for you.

Related

Getting error when trying to do the customized message in jQuery validate

I have been trying many times with JQuery for validating errors using customized messages, but I am still confused that where I am making the mistake.I have tried with the normal validating messages, but when I tried with the customized, it shows me an error.
Below is the sample code which i have tried so far and unsucessful in executing it.
<form id="myform">
<tr>
<td class="alpha">username</td>
<td>
<input type="username" type="text" value="">
</td>
</tr>
<br/>
<tr>
<td class="alpha">postcode</td>
<td>
<input type="postcode" type="text" value="">
</td>
</tr>
<input type="submit" />
</form>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$document.ready(function() {
$("#myform").validate({
rules: {
password: "required",
postcode: {
required: true,
minlength: 3
}
},
messages: {
username: {
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: {
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
});
});
As written, your code would not work with the default messages either.
Please read my comments in the code...
rules: {
password: "required", // <- input with name="password" (where is "password"?)
postcode: { // <- input with name="postcode"
required: true,
minlength: 3
}
},
messages: {
username: { // <- input with name="username"
required: "*Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
postcode: { // <- input with name="postcode"
required: "Field PostCode is required",
minlength: "Field PostCode must contain at least 3 characters"
}
}
The rules and messages objects' parameters are keyed by the name attribute of the input element. Your input elements do not contain any name attributes. The plugin mandates that all form inputs contain a unique name, and the plugin will not work without these.
You have invalid values for the type attribute. There are no such things as type="username" and type="postcode"; and you erroneously have more than one type attributes on each input, <input type="username" type="text" value="">
In your case, you don't even attempt to define any rules for a username field. You only have password and postcode within the rules object.
Fix your invalid HTML markup and JavaScript...
Remove all extraneous type attributes from each input.
Add a unique name attribute to each input.
Only reference your name attributes within rules and messages objects.
DEMO: jsfiddle.net/2tx6u7wf/

materialize cant set data-error

Im trying to use a library called jquery validate which just takes form inputs and returns success or error messages. With materialize I can use the data-error and data-success. I cant get the error working at all. I see it changes in the console but not on the webpage. Until I click off an input the go back to an input i know is wrong then it gives me an error warning
Even then the error is not persistent it disappears when i click onto another input again.
I can see by watching the inspector a valid class appears in the input.
I will post my code below any explanations why this happens would be appreciated:
$(document).ready(function() {
$("#signup_form").validate({
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
user_name: {
required: true,
maxlength: 3
}
},
//For custom messages
messages: {
first_name: {
required: "Enter your first name",
text: true,
minlength: "Enter at least 2 characters"
},
last_name: {
required: "Enter your second name",
text: true,
minlength: "Enter at least 2 characters"
},
user_name: {
required: "Enter a username",
maxlength: "Enter at least 3 characters"
}
},
errorClass: 'invalid',
validClass: "valid",
errorPlacement: function(error, element) {
$(element)
.closest("form")
.find("label[for='" + element.attr("id") + "']")
.attr('data-error', error.text());
}
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css" rel="stylesheet" />
<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.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
<form id="signup_form" class="col s6">
<div class="row">
<div class="input-field col s6">
<input id="user_name" type="text" name="user_name" class="validate">
<label for="user_name" data-error="" data-success="">User Name</label>
</div>
</div>
</form>
Too see the error start typing the click off the input and back on the type another letter its weird
Just incase someone comes across this in the future I wont take it down. Look through your inputs and remove the class 'validate'.
I'm not entirely sure but what I think happens is the validate class is looking at the input and testing for any of the markup contstraints i.e. max, min, step, type etc. This will add the valid class to all inputs regardless of the rules set in validate() because it fulfils the requirements made in markup.
So when we remove the validate class the validate library can act accordingly.

Validating field's with variable id. How to output errors. jQuery validation plugin

(1) I have next html:
<form method='post' action='' id='#countersForm'>
<label class='error' id='88'></label>
<input id="88" class="counter_input active" type="text" enabled="">
<label class='error' id='89'></label>
<input id="89" class="counter_input active" type="text" enabled="">
</form>
I need to validate this fields with jquery validation plugin.
How I can do this in case that fields are variables? For 1 user id will be 100 and 1000, for another 55 and 123. What jquery code I need to validate this.
if($("#countersForm").length)
{
$("#countersForm").validate({
rules: {
"89": {
required: true,
minlength: 2
}
},
messages: {
"89": {
required: "We need your email address to contact you",
minlength: jQuery.format("At least {0} characters required!")
}
}
});
}
(2) In what fields messages from 'messages' section will be printed? How I can specify them? I find many articles about this plugin at all, but there are not many (i still didn't find them) examples with output fields.
Maybe this code will help me:
$("#myForm").validate({
rules: {
field: {
required: true,
minlength: 10,
alphanumeric: true
}
},
messages: {
field: {
required: 'This is required.',
minlength: 'Please enter at least 10 characters.',
alphanumeric: 'No special characters.'
}
},
errorPlacement: function(error) {
$("#response").html(error);
}
});
But it place error in #responce element. I need to output error near input field. Can I somehow get id of current-validating-element and output error to label, connected to this element?
Try .insertafter()
errorPlacement: function(error, element) {
error.insertAfter(element);
}
ID must be unique use classes instead .
Two elements should not have same id.
Read Two HTML elements with same id attribute: How bad is it really?

How to validate input fields with a dot in name using the jquery validation plugin?

I'm using this jquery validation plugin
<s:textfield cssClass="form-control input-default" name="contest.title" id="title" placeholder="Enter Title"
/>
Validation doesn't work for this, but if I change the name to title - validation works.
I tried searching, but couldn't find a means to validate fields with a . in their name.
Please help
Update
Script
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#contestform").validate({
submitHandler: function(form) {
// return false; // block the default submit action
},
rules: {
title: {
required: true
},
link: {
required: true
},
startdt: {
required: true
},
enddt: {
required: true
},
descr: {
required: true
},
},
messages: {
title: "Please enter a title",
link: "Please enter the sponser redirection link",
startdt: "Please select start date",
enddt: "Please select end date",
descr: "Please enter description"
}
});
});
</script>
Part of the form
<form action="" enctype="multipart/form-data" method="post" id="contestform">
<s:hidden name="option" value="option"/>
<s:hidden name="contest.idcontest"/>
<div class="form-group">
<label for="title">Title</label>
<s:textfield cssClass="form-control input-default" name="contest.title" id="title" placeholder="Enter Title"
/>
</div>
You need to put the field names in qoutes. From the plugin documentation
Fields with complex names (brackets, dots)
When you have a name attribute like user[name], make sure to put the
name in quotes. More details in the General Guidelines.
The sample in the linked reference:
$("#myform").validate({
rules: {
// no quoting necessary
name: "required",
// quoting necessary!
"user[email]": "email",
// dots need quoting, too!
"user.address.street": "required"
}
});

Displaying multiple errors per field with jQuery Validation

I am looking to use the jQuery validator plugin to display multiple field level error messages at a time.
For example:
$("#myForm").validate({
rules: {
field: {
required: true,
minlength: 10,
alphanumeric: true
}
},
messages: {
field: {
required: 'This is required.',
minlength: 'Please enter at least 10 characters.',
alphanumeric: 'No special characters.'
}
},
errorPlacement: function(error) {
$("#response").html(error);
}
});
An input with "required", "minlength 10" and "alphanumeric", will only show the error for the minimum length if there are less than 10 characters, even though there may be a special character in the field.
I am looking for a solution to show all the messages for currently invalid rules on a given input field.
<label for="field">Field:</label>
<p>Please enter at least 10 characters.</p>
<p>No special characters.</p>
<input type="text" id="field" name="field" />
I appreciate any input on how to achieve this!
Thanks,
Danny

Categories

Resources