Submit / Validation Jquery - javascript

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;
};

Related

How can I fix my JS and jQuery to properly validate input?

I am completely brand new to JS and jQuery. I have written a basic html form to calculate values and am wanting to validate each input and test to see if it contains a non-zero value but I can't figure it out. I have spent much time searching before posting this. Remember I am completely new so take it easy on me, please. Here is my script to test the inputs.
$('#ppm_Pt').on('change', function () {
var input = $(this);
var is_num = input.val();
if (is_num)
{
$('#Calculate').prop("disabled", false)
}
else
{
$('#Calculate').prop("disabled", true)
}
});
I can get this to work to check if there is any input for ppm_Pt, but instead I am wanting to check all inputs of type number in my html form and instead of just checking for any value I want to test against nulls and 0 values. I know there is a way. I have tried using the each() method but was unsuccessful. Please help. Thanks.
You are doing an ID selection on an element if this is your form you would probably do something like:
$('#ppm_Pt').on('change', 'input', function () {
var input = $(this);
var is_num = input.val();
if (is_num !== '')
{
$('#Calculate').prop("disabled", true);
}
else
{
$('#Calculate').prop("disabled", false);
}
});

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;
});

How to get jQuery event handler return value

I have a link with id="something":
html
<a id="something" onclick="getReturnValue()"> Something </a>
javascript
function getReturnValue(){
//some validation
if(validation fails){
return false;
}else{
return true;
}
}
I need to get the return value when I use:
$("#something").click();
How can I get the return value for the event ?
Already onclick function is mentioned in the html tag. I wanted to use:
$("#something").click();
and from that I wanted to get return value.
As I have to use it in multiple place, I dont want to write getReturnValue() method again and again like:
click(function(){ getReturnValue() })
I need to do this
if($("#something").click() == true){
form.submit();
}
click() will call getReturnValue() which will do some validation. If the validation fails, it return false and I need not submit the form. If validation is true, I need to submit the form
To do some form validation, you can do something like that:
$('#myForm').submit(function(e) {
if () {//Validation rules failed
e.preventDefault(); //Prevent browsers from submitting
}
//Form is valid do nothing and let the form submit
});
Now on your button:
$("#something").click(function() {$('#myForm').submit();//Calls function from above});
What you can do is create a jQuery event object and pass that to the click handler.
var e = jQuery.Event('click');
$('#something').click(e)
if (e.validResult) {
//action
}
You'll have to modify the click handler somewhat to take an event object and set a validResult property if the validation is successful.
function getReturnValue(e) {
//some validation
if (valid) {
e.validResult= true;
}
}
Here is an example on how you can access return data from event handler.
var a;
$(document).on('a', function(e){
$(document).trigger(a = $.Event('sum', {datas: e.datas}));
});
$(document).on('sum', function(e){
return e.datas;
});
$(document).trigger($.Event('a', {datas: [1,2,3]}));
console.log(a.result);//[1,2,3]
You change it with your purpose. check here https://api.jquery.com/event.result/ for more details.
$("#something").click(function() {
var x = getReturnValue();
});
this is what you want?
LE: and this means your a changes to
<a id="something"> Something </a>
you're trying to run two different functions on a click event,
maybe you need remove the inline code (onclick="func()") and put this in your script
$("#something").click(
function(){
var returnValue = getReturnValue();
}
);
I don't really understand your question though...

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