Validating user input with try and catch with jQuery - javascript

I want to validate whatever the values of the inputs are using try and catch. Every time the user gives a wrong value I want a a message to appear next to the input box that filled wrong.
The problem is that the every time it executes, the wrong message appears in both input boxes and I don't want to put many conditions. I just want to make it as simple as possible. I don't have a clue what conditions I should use.
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i]);
} //for loop
function fn(exp, str) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
alert(e);
$("#empty1").fadeIn(3000);
$("#empty1").html(e);
$("#empty1").fadeOut(3000);
$("#empty2").fadeIn(3000);
$("#empty2").html(e);
$("#empty2").fadeOut(3000);
} //try and catch
} //function
}); //button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
Name<input id="name"><span id="empty1"></span></br>
</br>
Last Name<input id="lName"><span id="empty2"></span></br>
</br>
<button id='btn'>Click</button>
</body>
</html>

For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
<form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label><b>Password</b></label>
<input type="password" class="form-control" placeholder="Password" name="psw" id="psw">
</div>
<div class="form-group">
<label><b>Repeat Password</b></label>
<input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">
<span id='message'></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="save">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<script>
$("#myform").validate({
rules: {
psw: {
required: true
},
rpsw: {
equalTo: "#psw"
}
}
});
</script>

Since you want it according to what has been asked of you to do,
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i],i+1);
} //for loop
function fn(exp, str, no) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
//alert(e);
if($('#err').length==0)
$("#empty"+no).val('').addClass('error').after('<p style="display:inline;" id="err">'+e+'</p>');
} //try and catch
} //function
}); //button
});
where error class can have css like
.error{
border: 2px solid red;
background-color: #f7b9d9;
}

Related

can not assign HTML element to variable using js

I am trying to change the display property of some text using JS, upon button click.
I have confirmed that the function is firing and running correctly using debugger, but for some reason, I can't grab the specific element I need to change, and assign it to a variable. I also have jquery set up on the page.
I have tried using the console, and document.getElementById('warning-textID') returns the correct element, but when I try to set it to a variable in console, it returns undefined. Am I missing something super obvious here?
Here is the HTML, function and css.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
});
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if(enteredValue == validParam){
console.log('do the thing')
if(cookieCreated == false && enteredValue == validParam){
warning.innerText = "Please enable cookies";
warning.style.display = "";
return;
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "";
enteredValue.value = "";
return;
}
}
.warning-text {
color: red; text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper" >
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>
I fixed some mistakes and it worked.
//adding event listener
$(function() {
document.getElementById("submitdiscount").addEventListener("click", putCookie);
// click function
function putCookie() {
var enteredValue = document.getElementById("nameBox").value;
var validParam = "test";
var warning = document.getElementById("warning-textID");
var cookieCreated = false;
if (enteredValue === validParam) {
console.log('do the thing')
if (cookieCreated == false && enteredValue === validParam) {
warning.innerText = "Please enable cookies";
warning.style.display = "block";
return;
}
} else {
warning.innerText = "Please enter the correct code."
warning.style.display = "block";
enteredValue.value = "";
return;
}
}
});
.warning-text {
color: red;
text-align: center;
margin-bottom: 0px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="employee-code-input-wrapper" id="employee-code-input">
<div class="employee-code-input-header">
<h2>Enter the employee code you received via email</h2>
</div>
<div class="search-bar emplyoee-code-input-input-wrapper">
<input class="emplyoee-code-input-input" type="text" placeholder="Enter Employee Code" code="" id="nameBox" name="pass">
<button class="btn btn--submit-employee-form" value="Submit" id="submitdiscount" type="button">submit</button>
</div>
<h2 class="warning-text" id="warning-textID">
Please enter the correct code.
</h2>
</div>

Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong?
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
if ($('input').val().length > 0) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
Here's a modification of your code that checks all the <input> fields, instead of just the first one.
$(document).ready(function() {
validate();
$('input').on('keyup', validate);
});
function validate() {
var inputsWithValues = 0;
// get all input fields except for type='submit'
var myInputs = $("input:not([type='submit'])");
myInputs.each(function(e) {
// if it has a value, increment the counter
if ($(this).val()) {
inputsWithValues += 1;
}
});
if (inputsWithValues == myInputs.length) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
Vanilla JS Solution.
In question selected JavaScript tag.
HTML Form:
<form action="/signup">
<div>
<label for="username">User Name</label>
<input type="text" name="username" required/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" />
</div>
<div>
<label for="r_password">Retype Password</label>
<input type="password" name="r_password" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" />
</div>
<input type="submit" value="Signup" disabled="disabled" />
</form>
JavaScript:
var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
var disabled = false
inputs.forEach(function(input, index) {
if (input.value === '' || !input.value.replace(/\s/g, '').length) {
disabled = true
}
})
if (disabled) {
register.setAttribute('disabled', 'disabled')
} else {
register.removeAttribute('disabled')
}
})
Some explanation:
In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.
If you need to disable submit button until all required input fields are filled in - replace:
inputs.forEach(function(input, index) {
with:
required_inputs.forEach(function(input, index) {
where required_inputs is already declared array containing only required input fields.
JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/
You could try using jQuery Validate
http://jqueryvalidation.org/
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
And then do something like the following:
$('#YourFormName').validate({
rules: {
InputName1: {
required: true
},
InputName2: { //etc..
required: true
}
}
});
Refer to the sample here.
In this only input of type="text" has been considered as described in your question.
HTML:
<div>
<form>
<div>
<label>
Name:
<input type="text" name="name">
</label>
</div>
<br>
<div>
<label>
Age:
<input type="text" name="age">
</label>
</div>
<br>
<div>
<input type="submit" value="Submit">
</div>
</form>
</div>
JS:
$(document).ready(function () {
validate();
$('input').on('keyup check', validate);
});
function validate() {
var input = $('input');
var isValid = false;
$.each(input, function (k, v) {
if (v.type != "submit") {
isValid = (k == 0) ?
v.value ? true : false : isValid && v.value ? true : false;
}
if (isValid) {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
});
}
Try to modify your function like this :
function validate(){
if ($('input').val() != '') {
$("input[type=submit]").prop("disabled", false);
} else {
$("input[type=submit]").prop("disabled", true);
}
}
and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this :
<input type = "text" name = "test" id = "test" onkeyup = "validate();">
Not so sure of this but it might help.
Here is a dynamic code that check all inputs to have data when wants to submit it:
$("form").submit(function(e) {
var error = 0;
$('input').removeClass('error');
$('.require').each(function(index) {
if ($(this).val() == '' || $(this).val() == ' ') {
$(this).addClass('error');
error++;
}
});
if (error > 0) {
//Means if has error:
e.preventDefault();
return false;
} else {
return true;
}
});
.error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form>
<form action="google.com">
<input type="text" placeholder="This is input #1" class="require" />
<input type="text" placeholder="This is input #2" class="require" />
<input type="submit" value="submit" />
</form>
</form>
Now you see there is a class called require, you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form!
Modify your code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">
<script>
$(document).ready(function (){
validate();
$('input').on('keyup', validate);
});
function validate(){
$("input[type=text]").each(function(){
if($(this).val().length > 0)
{
$("input[type=submit]").prop("disabled", false);
}
else
{
$("input[type=submit]").prop("disabled", true);
}
});
}
</script>
function disabledBtn(_className,_btnName) {
var inputsWithValues = 0;
var _f = document.getElementsByClassName(_className);
for(var i=0; i < _f.length; i++) {
if (_f[i].value) {
inputsWithValues += 1;
}
}
if (inputsWithValues == _f.length) {
document.getElementsByName(_btnName)[0].disabled = false;
} else {
document.getElementsByName(_btnName)[0].disabled = true;
}
}
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br>
<input type="submit" value="Join" id="yyyyy" disabled name="fruit">

Cannot make simple jQuery work

I'm learning jQuery, but I can't make this example work. I know it's quite simple but I don't know what I'm missing. I'm trying to add the class "invalid" in a textfield.
<script src="../jquery/jquery-1.8.2.js"></script>
<script src="../jquery/jquery.ui.effect.js"></script>
<script>
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
</main>
There is a syntax error in your Javascript. The corrected Javascript:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
return false;
}
});
});
Fiddle here: https://jsfiddle.net/s9x1Ldfm/
However I would add the return does not make a lot of sense. It returns false sometimes and void others. What exactly are you trying to do with that?
So, the problem in your code is that you are missing some closing ')' and '}'. The following will make it correct:
$(function() {
$('button.btn').on('click', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
} // end of for
return false;
} // end of if
}); // end of click
});
You can try to debug your javascript by using the debugger in the browser, by clicking F12. In the Element/Console section, you can see the error messages you have in your code. It will give you some hints regarding the error you have. Also, if you do not have any syntax problem, you are able to use
debugger;
In your code and when you run it in your browser with the debugger mode (F12), you can debug step by step into your code and look at the values of the variables and see how your program is behaving.
But, if in your code you just want to see if the input text is empty or not by the time the user click the button, you can try the following snippet:
<script>
$(function() {
$('#create_task').on('click', function() {
event.preventDefault(); // prevents submission
if ($('.validate').val().length > 0) {
$('.invalid').hide();
} else {
$('.invalid').show();
}// end of if
}); // end of click
});
</script>
<main>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<div class="invalid" style="display:none">Invalid input</div>
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button id="create_task" class="btn" type="submit" name="createTask">Create Task</button>
</form>
</main>
Pay attention how I changed the name of button to id to detect the button without extra validation. I hope it helps.
Use event.preventDefault() to prevent the form submission.
Check out his fiddle.
Here is the snippet.
$('button.btn').click(function(event) {
event.preventDefault();
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
});
.invalid {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate" />
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</form>
Your code has number of issues. First of all, if you want to capture form submission use .submit function and not click on button. Otherwise, you can remove the form tag and capture the click on button element.
Additionally, you can loop through jQuery object using .each. Using for is definitely faster as it is a native JavaScript functionality. I have made a proof of concept on this jsfiddle.
See this code.
$(function () {
$('button.btn').on('click', function () {
if ('create_task' == $(this).val()) {
$('.validate').each(function (i, e) {
if ("" == $(e).val()) {
$('.validate').addClass('invalid');
} else {
$('.validate').removeClass('invalid');
}
})
}
})
});
.invalid
{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="row">
<div class="input-field col s6">
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
<input name="name" type="text" class="validate">
<label class="active" for="task_name">Task Name</label>
</div>
</div>
<button class="btn" type="submit" value="create_task" name="createTask">Create Task</button>
</main>
You have a syntax error as you haven't closed the $(function(){ in your script.
Moreover move your return false to an outer block (so that you'll prevent the default submit behaviour of the button) AND, use submit (which is same as using .submit() method) event as such:
$(function() {
$('button.btn').on('submit', function() {
if ('create_task' == $(this).val()) {
for (var i = 0; i < $('.validate').length; i++) {
if ("" == $('.validate').eq(i).val()) {
$('.validate').eq(i).addClass('invalid');
} else {
$('.validate').eq(i).removeClass('invalid');
}
}
}
return false;
});
});
NOTE: If you wanted, you could change the type='submit' to type='button' while triggering the click event, thus ridding you of returning false in your JavaScript code.

Locally storing form to set last current form to the new current form

I know the title sounds quite difficult to understand (weird) but here is it's explanation:
Suppose I have 2 forms on my page. A button's click hides a current form and then shows up another. I refresh the page. Now I want the form which was before the refresh the current form to be after the refresh to be current form aswell. I know that it can be done by using localStorage but I don't know how. :P
Code (HTML):
<div class="span5">
<!-- Row's 2nd Column holding the sign-in/sign-up form -->
<form action="login.php" method="post" class="form-signin" id="login_frm">
<h2 class="form-signin-heading">Login</h2>
<input class="input-xlarge" type="text" placeholder="Username" name="username" />
<input class="input-xlarge" type="password" placeholder="Password" name="password" />
<br/>
<input type="submit" name="submit_login" value="Login" class="btn btn-primary" />
</form>
<form action="login.php" method="post" class="form-signin hide" id="register_frm">
<h2 class="form-signin-heading">Register</h2>
<input class="input-xlarge" type="text" placeholder="Username" name="username" />
<input class="input-xlarge" type="password" placeholder="Password" name="password" />
<input class="input-xlarge" type="password" placeholder="Confirm Password" name="confirm_password" />
<br/>
<input type="submit" name="submit_register" value="Register" class="btn btn-primary" />
</form>
</div>
CSS: Using bootstrap :)
JS:
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(document).ready(function () {
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$(this).text('Register');
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$(this).text('Login');
}
});
});
Well, here should be a working solution. I've marked new code with a comment.
var registerBtn = $("#register_button"); //storing the hyperlink of register in a variable
var i = 0; //click count
$(document).ready(function () {
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
$("#register_frm").fadeToggle('fast', function () {
$("#login_frm").fadeToggle('fast');
});
$(this).text('Register');
localStorage.setItem("form", "login"); // < NEW CODE
} else {
$("#login_frm").fadeToggle('fast', function () {
$("#register_frm").fadeToggle('fast');
});
$(this).text('Login');
localStorage.setItem("form", "register"); // < NEW CODE
}
});
// v NEW CODE v
if (localStorage.getItem("form") == "register") {
$("#register_button").click();
}
// ^ NEW CODE ^
});
Here's a solution, although it does not work very well as a jsFiddle because of the page refresh due to the action method. PS. No need for local storage (in the conventional sense), these two variables can just be a couple of data properties of the window itself.
$(document).ready(function () {
var registerBtn = $("#register_button");
var rform = $('#register_frm');
var lform = $('#login_frm');
lform.show();
rform.hide();
var i = 0;
$("#register_button").on('click', function (e) {
e.preventDefault();
i++;
if (i % 2 === 0) {
rform.find('input[name = "username"]').val(window.data('username'));
rform.find('input[name = "password"]').val(window.data('password'));
$("#register_frm").fadeOut('fast', function () {
$("#login_frm").fadeIn('fast');
});
$(this).text('Register');
} else {
window.data('username', val('rform.find(input[name = "username"]'));
window.data('password', val('rform.find(input[name = "password"]'));
$("#login_frm").fadeOut('fast', function () {
$("#register_frm").fadeIn('fast');
});
$(this).text('Login');
}
});
});

Validate Dynamically Added Input fields

I have used this jquery validation plugin for the following form.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var obj = document.getElementById("list").cloneNode(true);
document.getElementById('parent').appendChild(obj);
}
</script>
<form id="commentForm" method="get" action="">
<p id="parent">
<input id="list" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
When the add button is clicked a new input is dynamically added. However when the form is submitted only the first input field is validated. How can i validate dynamically added inputs?
Thank you...
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
Reset form validation after adding new fields.
function resetFormValidator(formId) {
$(formId).removeData('validator');
$(formId).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(formId);
}
You need to re-parse the form after adding dynamic content in order to validate the content
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
Modified version
jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.
$(document).find('#add_patient_form').validate({
ignore: [],
rules:{
'email[]':
{
required:true,
},
},
messages:{
'email[]':
{
'required':'Required'
},
},
});
In regards to #RitchieD response, here is a jQuery plugin version to make things easier if you are using jQuery.
(function ($) {
$.fn.initValidation = function () {
$(this).removeData("validator");
$(this).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(this);
return this;
};
}(jQuery));
This can be used like this:
$("#SomeForm").initValidation();
In case you have a form you can add a class name as such:
<form id="my-form">
<input class="js-input" type="text" name="samplename" />
<input class="js-input" type="text" name="samplename" />
<input class="submit" type="submit" value="Submit" />
</form>
you can then use the addClassRules method of validator to add your rules like this and this will apply to all the dynamically added inputs:
$(document).ready(function() {
$.validator.addClassRules('js-input', {
required: true,
});
//validate the form
$('#my-form').validate();
});
$('#form-btn').click(function () {
//set global rules & messages array to use in validator
var rules = {};
var messages = {};
//get input, select, textarea of form
$('#formId').find('input, select, textarea').each(function () {
var name = $(this).attr('name');
rules[name] = {};
messages[name] = {};
rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
if (name === "email") {
rules[name].email = true;
//messages[name].email = "Please provide valid email";
}
else if(name==='url'){
rules[name].required = false; // url filed is not required
//add other rules & messages
}
});
//submit form and use above created global rules & messages array
$('#formId').submit(function (e) {
e.preventDefault();
}).validate({
rules: rules,
messages: messages,
submitHandler: function (form) {
console.log("validation success");
}
});
});
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>

Categories