Form validation using jquery and javascript codes - javascript

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)

Related

Input live check

i got a input field and a button
<input required id="solution" name="solution" type="text" placeholder=""class="form-control input-md">
<button style="background-color:#da251d;" id="sendForm" name="sendForm" class="btn btn-success">Send</button>
Now i want to check the input Field for an value, when the value is incorrect, the button should be disbaled, i try it with js like this
$(document).ready(function(){
$(“#solution”).keyup(function(){
if($(this).val() == ‘value’) {
$(‘#sendForm’).attr(‘disabled’,‘disabled);
}
else {
$(‘#sendForm’).removeattr(‘disabled’);
}
});
});
But it dont work, can you help me pls?
i think you did the typo error on .removeAttr
$(document).ready(function(){
$("#solution").keyup(function(){
if($(this).val() == "value") {
$("#sendForm").attr("disabled","disabled");
}
else {
$("#sendForm").removeAttr("disabled");
}
});
});
You should try to use the "change" or the "input" event. It would look similar to
$('#solution').on('change', function(){
// validation & toggle button state
})
For further event documentations:
change
Easy one!
The code does not work since you're using quotation marks (”) but what you should be using are the String marks (" or ').
The working code:
$(document).ready(function(){
$("#solution").keyup(function(){
if($(this).val() == 'value') {
$('#sendForm').attr('disabled', 'disabled');
}
else {
$('#sendForm').removeAttr('disabled');
}
});
});
Jsbin
Hey this is working fine ,
$("#solution").keyup(function(){
if($(this).val() == 'value') {
$('#sendForm').attr('disabled',false);
}
else {
$('#sendForm').attr('disabled',true);
}
});
You can use attr method for setting disabled property as true or false as per your need.
demo

Swapping classes when input is not valid, jquery

Im only starting to learn jquery, trying to validate my html forms.
I want inputs to be red when there is no string so I set all inputs under class= "valid" to start and when empty field being submitted I want jquery to swap valid class to not_valid.
I manage to do that part but I need those classes back to normal when form is re-submitted.
Can anyone please help me? thx
$('.submit_signup').click(function(){
var abort = false;
$('not_valid').remove();
$(':input[required]').each(function(){
if($(this).val()===''){
$(this).removeClass('valid').addClass('not_valid');
abort = true;
}
});
if(abort){
return false;
}else{
return true;
}
});
Unless I misunderstand, you can just add an else to your if, and replace not-valid with valid if the field isn't empty.
Pretty simple!
$('.submit_signup').click(function(){
var abort = false;
// do not forget the dot for classes
$('.not_valid').removeClass('not_valid');
// check inputs
$(':input[required]').each(function(){
if($(this).val()===''){
$(this).removeClass('valid').addClass('not_valid');
abort = true;
}
});
// ! means not
return !abort;
});

Submit / Validation Jquery

Im trying to validate a form at the point of clicking submit. There are a number of inputs which need validating which are all assigned the class .ipv4val. The issue I have is that I cant seem to add the 'bad' class to the single input element that has failed the validation ?
$("form").submit(function() {
var REGEX = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
if (REGEX.test($(".ipv4val").val())) {
return true;
}
else {
$(this).addClass("bad");
return false;
}
Any ideas ?
Look out for your use of: $(this).addClass("bad")
$(this) is the form element at the time of its execution. Try using the element ID of the input.
Have you considered the jquery.validate plugin, instead of rolling your own validation?
Try it this way:
$("form").submit(function() {
var REGEX = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
var ok=true;
$(".ipv4val").each(function(){
if (!REGEX.test($(this).val())) {
$(this).addClass("bad");
ok = false;
}
});
return ok;
};

Trying to dynamically validate fields with jQuery - custom function

I'm working on a validation function in jQuery and am getting a bit stuck. I've got a working version that is very lengthy and full of hardcoded form values which I'm trying to avoid. Here's what works, currently:
$(document).ready(function(){
var fname = $("#formFName");
var lname = $("#formLName");
fname.blur(validateFName);
lname.blur(validateLName);
function validateFName(){
if(fname.val().length > 0){
fname.removeClass("req_error");
return true;
}
else {
fname.addClass("req_error");
return false;
}
}
function validateLName(){
if(lname.val().length > 0){
lname.removeClass("req_error");
return true;
}
else {
lname.addClass("req_error");
return false;
}
}
});
That part works fine for those two fields but I'd like to encapsulate the whole thing in a function that's a bit easier to maintain. Something like this:
$(document).ready(function(){
$("#first_name").blur(validateField("first_name","text"));
$("#last_name").blur(validateField("last_name","text"));
$("#email_address").blur(validateField("email_address","email"));
function validateField(formfield, type){
var field = $("#" + formfield);
switch(type) {
case "text":
if(field.val().length > 0){
field.removeClass("req_error");
return true;
}
else {
field.addClass("req_error");
return false;
}
break;
case "email":
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(field.val())) {
field.removeClass("req_error");
return true;
else {
field.addClass("req_error");
return false;
}
break;
}
}
});
However, when I do that I get the following error in Firefox's JS error log:
Error: ((f.event.special[r.origType] || {}).handle || r.handler).apply is not a function
Source File: /scripts/jquery-1.7.1.min.js
Line: 3
A quick Google for that error hasn't yielded anything that means anything to me, unfortunately. I've tried alerts in various spots and doing so has verified that the proper form field names are indeed being passed where there supposed to be, but as I'm fairly new to jQuery (and not great at JavaScript) I'm at a bit of a loss here.
Thanks to anyone who can point me in the right direction. Also, if anyone thinks that I'm going about this in the wrong way, I'm more than happy to change. I tried using the jQuery validation plugin but I'm also using some dynamically created fields and unfortunately the plugin prevents the visitor from submitting the form when hidden required fields are involved.
Sounds like you could simplify this by attaching behavior instead of specific elements:
<input type="text" id="someId" class="validate-text" />
<input type="text" id="someOtherId" class="validate-email" />
$('.validate-text').live('blur', function()
{
$(this).removeClass('req_error');
if($.trim(this.value).length < 1)
$(this).addClass('req_error');
});
$('.validate-email').live('blur', function()
{
// Same thing with the email validation logic
});
This way, you dont need to attach specific event handlers to your elements and instead use those handlers to check the behavior you want. Then you simply mark HTML elements with specific classes to mark the validation mode you want.
Assuming I understood your question correctly.
You can't pass a function invocation expression to .blur(). You can pass an anonymous function constructor:
$("#first_name").blur(function () {validateField("first_name","text");});
Or pass the name of a function:
function validateFirstName() {
validateField("first_name","text");
}
* * *
$("#first_name").blur(validateFirstName));
#Tejs's suggestion to use classes to attach validators is a good one, as well.

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