Custom form validation using jquery plugin, based on attributes - javascript

I am using Jquery valdiation plugin for validating the form at client side. But I want to do the validation like.
<input type="text" id="txtInf" regex="/some regular expression/" error="Inf is mandatory"></inf>
here regex and error are custom attributes. Field will be validated against the given regular expression in regex and if the regular expression text fails then error meessage should be shown.
I tried to add a method to validator like this.
$("*[regex]").each(function () {
$.validator.addMethod($(this).attr('id'), function () {
return this.optional($(this)) || $(this).attr('regex').test($(this).text());
}, $(this).attr('error'));
});
But there is some issue, with the approach. Please let me know, if I am thinking it right.
If there is some other approach in your mind, please let me know. Any thought process is welcomed.

I haven't used that plugin, but it looks like you'll get an error from the use of test().
$(this).attr('regex').test($(this).text());
should be
var regEx = new RegExp($(this).attr('regex'));
regEx.test($(this).text());

custom form validation in bootstrap is possible using few lines of code
// Add below code in html
<form id="addForm" action=" " method="post" class="needs-validation" novalidate> </form>
// add this in script tag
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
document.getElementById("btn_inject").addEventListener("click", function(event) {
//form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})
();
//you will also need this to make the text boxes back to dismiss the validation
$("#Modalidname").on('hide.bs.modal', function() {
$("#Formidname").removeClass('was-validated');
});

Related

How to do javascript bootstrap form validation?

There is a standard bootstrap validation script:
'use strict'
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
But it only checks if the values ​​are empty. And I need to additionally check, for example, that the input field with id=year has four digits.
I know about "pattern" attribute, but Safari doesn't support it. I need a javascript solution with a code example.

Adding validation to dynamic forms

I pull what to display on a particular form from my database, so the form elements are dynamic.
I display radio buttons, or checkboxes or textboxes/textareas depending on how I want the form to display.
Before someone submits the form, I have to validate that each form entry (radio, checkbox, textbox etc) has been selected.
How can I insert validation to these dynamic form elements?
Example:
<input type="checkbox" id="#formInputId" name="#formInputName" value="#element.Id" />
to get started, you can also inject JSON/Javascript into the view. Though this is not preffered because then you wont be able to make a separate js file out of it. But in case of validation of dynamic forms i did this earlier.
since your form ids are coming from the database you know Id of each control therefore you can identify each element separately using jquery.
jquery validation plugins makes it very easy to add validation rules. So you just make the validation rules server side with something like this.
forEach(FormElement element in Model.FormElements){
dynamic rules = new ExpandoObject();
//set all the rule here.
ViewBag.ElementId = rules;
}
basic rules structure is given here.
Then inside the view when you are rendering the controls. check for
#if(ViewData.ContainsKey("[ElementId]")){
//if it exists
//inject json using newtonsoft json
<script>
$('##Html.raw([ElementId])').rules("Add", JsonConvert.SerializeObject(ViewData["ElementId"]))
</script>
}
Have you looked at the jquery validation plugin? Why try to reinvent the wheel. It's pretty simple to use.
Check this Demo
Here is the link to the official docs. http://jqueryvalidation.org/documentation/
Html
<form id="myform">
<input name="product[0][name]" id="form_product[0][name]" data-rule-required="true" />
<input name="product[1][name]" id="form_product[1][name]" data-rule-required="true" />
<input name="product[2][name]" id="form_product[2][name]" data-rule-required="true" />
<br/>
<br/>
<br/>
<input type="submit" />
add one field
Validation Documentation
css
#docs {
display: block;
position: fixed;
bottom: 0;
right: 0;
}
js
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
$('button').one('click', function () {
$('#myform').append('<input name="product[3][name]" id="form_product[3][name]" data-rule-required="true">');
});});
DEMO jsfiddle HERE
You should be able to parse the elements dynamically with the unobtrusive validation, however you'll need to add the appropriate attributes to trigger the appropriate validation first. Fundamentally it's very similar to what's happening in this question where they are adding elements dynamically by javascript.
If you can output a json blob of validations you can use this: https://github.com/parris/iz#json
It will let you specify a JSON blob of rules as such:
var rules = {
'cost': [
{
'rule': 'between',
'args': [17, 1000],
'error': 'The cost must be between 17, 1000'
},
{
'rule': 'required',
'error': 'You must specify a cost'
},
],
'producer.id': [
{
'rule': 'int',
'error': 'Producer ID must be an int'
}
],
'producer.name.first': [
{
'rule': 'alphaNumeric',
'error': 'Must be names and numbers'
}
]
};
Then collect your values and validate like this:
are(rules).validFor({
cost: 20,
producer: {
id: 1,
name: {
first: 'bob'
}
}
});
It has some built in validations that should pretty closely match what you need. If not, you can shim in some custom validations.
Note: Iz, is a library I wrote, and yes I am totally pitching it to you right now.
The JQuery Validate plugin should work (see http://jqueryvalidation.org).
It sounds like all you need is to mark all fields required, so you can add a required rule to them by using a class, which would avoid having to coordinate ids/names of your dynamic elements between the model and the javascript.
Change your input line to:
<input type="checkbox" id="#formInputId" name="#formInputName"
value="#element.Id" class="requiredField" />
Then in your javascript:
$(document).ready(function() {
var form = $( "#MyForm" );
form.validate();
jQuery.validator.addClassRules('requiredField', {
required: true
});
form.on('submit', function () {
if (form.valid()) {
form.submit();
}
});
});
You can also check validity of individual elements by using (selector).valid(). You can add other validation rules (besides required) by adding to the list of class rules.
You could also use Jquery Validate engine .
In which, you just have to manage class attribute of the dynamic element.
I suggest you, you could use Hook of Jquery Validate Engine.
It will be easy for you.
I have recently answered a question where we do no of things with jQuery, if you want to user custom jQuery, take reference as follows:
On form element you can use recursive code for ex: in case of a checkbox
$(document).ready(function () {
$('#new_user_form *').filter(':checkbox').each(function(){
if(this.id=='row1' && this.value=='3') {
} else {
$(this).attr("checked",false);
}
});
});
Will work same for other type of element i.e input, radio etc.
On selecting a checkbox disable spefic checkboxes
Review above for more, comment for more info or a small demo form.
i have achieved the same requirement using jQuery Validation Plugin
Place the following code in script section of your page.
you need to add the form-data class to your form and add required_field while adding the elements to page.
var validator = null;
$(document).ready(function () {
try {
var validatedForm = $(".form-data");
validator = validatedForm.validate && validatedForm.validate({
rules: {
required_field: {
required: true
}
},
messages: {
required_field: {
required: " "
}
},
errorElement: "span",
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();
},
highlight: function (element) {
// do something like
$(element).closest('...').removeClass('success').addClass('error');
},
unhighlight: function (element) {
// do something like
$(element).closest('...').removeClass('error');
},
submitHandler: function(form) {
// submit form
form.submit();
}
success: function (element) {
// do something like
$(element).closest('...').removeClass('error').end().remove();
},
onfocusout: function (element) {
$(element).valid();
},
});
$.each($(".required_field"), function (index, value){
$(value).rules( "add", {
required: true,
messages: {
required: " "
}
});
});
} catch(err) {
console.log("javascript error", err);
}
});
While submitting you can check if the form is valid or not:
if($('#formId').valid()) {
...
i guess the best way is make your client-side validation using $.validate plugin and in your POST action create methods to validate your data. I always suggest to not mix javascript with csharp, or others places, to maintains things organized.

Form validation using jquery and javascript codes

i am trying to validate my form for empty fields but i am not sure what code i should use can someone please direct me
i have tried the following code but its not working
$("validate").submit(function(event){
$(".offset2").each(function(index) {
if ($(this).val() == 0) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
event.preventDefault();
}
});
});
Just use a plugin.... More flexibility as you grow.
Here's free one after 1 minute of google.
http://jqueryvalidation.org/
Check this
if ($(this).val().length == 0) { // .length is missing in your code
// Show Error
}
// Or
if (!$(this).val()) { // Empty string is consider as false type in JavaScript
// Show Error
}
Try this,
$(function(){
$("validate").submit(function(event){
event.preventDefault();
var status=true;
$(".offset2").each(function(index) {
if (!$(this).val()) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
status=false;
}
});
return status;
});
});
aren't you missing a "#" before "validate".
$("#validate").submit(function(event){
$(".offset2").each(function(index) {
if ($(this).val() == 0) {
$("#error").css({"display": "inline"}).text("Some of the fields are empty");
event.preventDefault();
}
});
}
);
http://api.jquery.com/submit/
I would definitely recommend H5Validate http://ericleads.com/h5validate/
It allows you to use the proper HTML5 attributes for validation.
#CodeMonkeyForHire suggested using a Plugin.
The most used one is jQueryValidation. It will let you write markup like this:
<input id="cname" name="name" minlength="2" type="text" required/>
And then on your submit button you make one single call to validate all elements inside the form:
$("#commentForm").validate();
There are many other frameworks like ParselyJs or ValidateJs that you can try out.
P.S. Google is your friend, always look for plugins (probably someone else had the same problem you did)

Prevent multiple submits with Javascript and Prototype

I try to prevent multiple submits in HTML forms using Javascript through Prototype API. Here is the snippet I use to solve this problem :
function preventMultipleSubmits() {
this.select('input[type="submit"]').invoke('disable');
return true;
}
document.observe('dom:loaded', function() {
var forms = $A(document.getElementsByTagName('form'));
forms.each(function(form) {
form.observe('submit', preventMultipleSubmits)
});
});
The problem with that snippet is that submitting a form doesn't call the server side anymore. I know that IE browsers doesn't support CCS selectors very well, but the problem concerns Firefox too, and I'd like to focus on FF first.
The environnement and tools :
Firefox 13.0
Prototype 1.6.1
this.select('input[type="submit"]').invoke('disable');
This appears to just add the disabled attribute to the submit button. You can still get it to submit with enter for one-field forms.
You might try something like this:
<script type="text/javascript">
function preventMultipleSubmits(event) {
if (this.hasClassName('allow-one-time-submit')) {
this.removeClassName('allow-one-time-submit');
// don't stop the event
} else {
alert('You already submitted');
event.stop();
}
}
document.observe('dom:loaded', function() {
var forms = $A(document.getElementsByTagName('form'));
forms.each(function(form) {
// add Class Name to each and every form on load
form.addClassName('allow-one-time-submit');
form.observe('submit', preventMultipleSubmits)
});
});
</script>
<form action="http://www.example.com/path/to/action" class="allow-one-time-submit">
<input type="text">
<input type="submit" value="Submit">
</form>

how to check if a form is valid programmatically using jQuery Validation Plugin

I have a form with a couple of buttons and I'm using jQuery Validation Plugin from http://jquery.bassistance.de/validate/. I just want to know if there is any way I can check if the form is considered in valid state by jquery validation plugin from anywhere in my javascript code.
Use .valid() from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected
elements are valid. validate() needs to be called on the form before
checking it using this method.
Where the form with id='form_id' is a form that has already had .validate() called on it.
2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:
npm install jquery-html5-validity
Then:
var $ = require('jquery')
require("jquery-html5-validity")($);
then you can run:
$('.some-class').isValid()
true
#mikemaccana answer is useful.
And I also used https://github.com/ryanseddon/H5F. Found on http://microjs.com. It's some kind of polyfill and you can use it as follows (jQuery is used in example):
if ( $('form')[0].checkValidity() ) {
// the form is valid
}
For a group of inputs you can use an improved version based in #mikemaccana's answer
$.fn.isValid = function(){
var validate = true;
this.each(function(){
if(this.checkValidity()==false){
validate = false;
}
});
};
now you can use this to verify if the form is valid:
if(!$(".form-control").isValid){
return;
}
You could use the same technique to get all the error messages:
$.fn.getVelidationMessage = function(){
var message = "";
var name = "";
this.each(function(){
if(this.checkValidity()==false){
name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
}
})
return message;
}
valid() method.
http://docs.jquery.com/Plugins/Validation/valid
iContribute: It's never too late for a right answer.
var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
form.submit();
}else{
console.log("Required field missing.");
}
This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.
For Magento, you check validation of form by something like below.
You can try this:
require(["jquery"], function ($) {
$(document).ready(function () {
$('#my-button-name').click(function () { // The button type should be "button" and not submit
if ($('#form-name').valid()) {
alert("Validation pass");
return false;
}else{
alert("Validation failed");
return false;
}
});
});
});
Hope this may help you!
In case you're validating before submitting the form:
$(function(){
$('.needs-validation').on('submit', function(event){
if(!event.target.checkValidity()){
// Form didn't pass validation
event.preventDefault();
$(this).addClass('was-validated');
}
})
})
You can't use $('form')[0].checkValidity() with multiple forms in the view.

Categories

Resources