Remove literals from input value before validation and submit - javascript

I have a form with a required phone number field that looks like this with the maskedinput plugin
(999) 999-9999
I want the jquery validation to ignore the literals in order to validate this. Also, i want the literals to be removed before the form is submitted. But if there is a validation error i still want the maskedinput plugin activated so the format looks correct for the user still.
I figure i could edit the regex for the validation but then when the form is submitted the literals will still be on there.
Let me know i need to explain this better.
Any Ideas? I'm pretty new to jquery and all so detailed solution would be great.
My javascript code is this
$(document).ready(function(){
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "US Phone Number Required");
$("#valform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("Please correct the required field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
phone: {
required: ""
}
},
rules: {
phone: {
required: true,
phoneUS: true
},
},
});
$("#phone").mask("(999) 999-9999",{placeholder:" "});
});

You could remove the other characters before submitting the form using js
This code will remove the forbidden character from the input as soon as its entered.
The input field has the class "numbers". This binds the "keyup" event to that input field and calls a function called "handleInputKeyUp"
$(".numbers").bind("keyup", handleInputKeyUp);
The function:
function handleInputKeyUp(e){
var temp = e.currentTarget.value;
temp = temp.replace(/[^\d-]/g, "");
e.currentTarget.value = temp;
}
This code removes all but digits and - from the input field.

Related

Validating React-Bootstrap-Typeahead input

I am using a validation function in my form, that checks whether a field is empty or not. This works for normal text input boxes, but not for the Typeahead box.
I want to check if the Typeahead box is empty, and if it is, display an error message i.e. this.state.industryError
This is my state:
state = {
name: "",
industry: [],
nameError: "",
industryError: "",
}
And this is my Typeahead form element:
<Form>
<Label>Industry</Label>
<Typeahead
id="industryMultiSelect"
multiple
options={industries}
placeholder="Select industry..."
onChange={this.handleTypeaheadChangeIndustry} />
<div>
{this.state.industryError} // Where the error message appears
</div>
</Form>
My validate function is as follows:
validate = () => {
let nameError = "";
let industryError = "";
if(!this.state.name) { // Checks if field is empty
nameError = "Please enter a name";
}
if(this.state.industry === []) { // I think this is the problem
industryError = "Please enter an industry";
}
if (nameError || industryError) {
this.setState({nameError, industryError});
return false;
}
return true;
};
This is handleChange function I call for the typeahead:
handleTypeaheadChangeIndustry = selected => {
const industry = selected.map(option => option.value);
this.setState({industry})
};
It works fine with the name field because it equals an empty string. But with the Typeahead, it's not a string, and so I'm unsure what to set this.state.industry to.
Any help or advice is much appreciated, and I can quickly update my answer if you need more detail.
It's a little hard to pinpoint why your code isn't working without seeing everything. That said, I created a sandbox which I believe does what you're after using the code you posted above:
https://codesandbox.io/s/react-bootstrap-typeahead-form-validation-686qe
As #ravibagul91 notes, you should be using one of
if (this.state.industry.length === 0) { ... }
if (!this.state.industry.length) { ... }
rather than
if (this.state.industry === []) { ... }
Using the latter in the sandbox I posted causes the code not to work, while things work fine when using either of the first two.

How to add new validations to Marketo form

As am not good with JS and Jquery, am struggling to add new validation rule to the Marketo form, which shows error message when tried to submit the form leaving any field empty along with I need to validate the FirstName and LastName fields to allow only the alphabetic characters and should through a error message when numeric characters are entered.
Below is my Marketo LP: http://qliktest.qlik.com/Vinu-Test1_Reg_Form.html
Here is an example of custom email validation. You can put the custom code in whenReady function.
MktoForms2.whenReady(function(form) {
function isEmailValid(email) {
RE_EMAIL_ASCII_PUBLIC = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/;
return RE_EMAIL_ASCII_PUBLIC.test(email);
}
form.onValidate(function() {
var values = form.vals();
if (values.Email) {
if (!isEmailValid(values.Email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage(
// write your message here
"Must be valid email.",
emailElem
);
} else {
form.submitable(true);
}
}
});
If you mark the fields as "required" in Marketo there is already logic built in that will take care of the validation for you. If you want to create some custom validation logic, I.E. only allowing alphabetic characters in the fields, you need to use the Marketo Forms 2.0 Javascript API (http://developers.marketo.com/documentation/websites/forms-2-0/)
Here's an example of validating a Marketo form field using the API:
MktoForms2.whenReady(function (form) {
//listen for the validate event
form.onValidate(function() {
// Get the values
var vals = form.vals();
//Check your condition
if (vals.Country == "USA" && vals.vehicleSize != "Massive") {
// Prevent form submission
form.submittable(false);
// Show error message, pointed at VehicleSize element
var vehicleSizeElem = form.getFormElem().find("#vehicleSize");
form.showErrorMessage("All Americans must have a massive vehicle", vehicleSizeElem);
}
else {
// Enable submission for those who met the criteria
form.submittable(true);
} }); });

input file type error validation not working using jquery

Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example

How to validate pre populated input field with jQuery validate?

I have a form with fields which are pre populated with data from database, as I need to change phone number according to new data format schema, I also need to immediately fired up validation for pre populate input fieldd.
My JS code is as follows:
Method to validate HR phone numbers according to new schema:
$.validator.addMethod("mobileHR", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^\+[0-9]{1,3}\.[0-9]{1,14}$/);
}, "Unesite broj u fromatu: +385.111234567");
And function calls:
$(document).ready(function () {
// initialize validation
$('.form-horizontal').validate({
// set immediate validation, on event code 9
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
"contactdetails[Registrant][Phone]": {
required: true,
mobileHR: true
}
},
messages: {
"contactdetails[Registrant][Phone]": {
required: "Molimo unesite broj telefona"
}
}
});
});
Input field is like these, and value parameter is allready populated, as data is fetched from database.
<div class="controls">
<input kl_virtual_keyboard_secure_input="on" name="contactdetails[Registrant][Phone]" value="011123456" size="30" class="Registrantcustomwhois" type="text">
</div>
Now I want to warn a user editing data, even if he doesn't change data in desired input field, to update format of his phone number, so I basically want to call validate() function at the document has been loaded.
Fiddle with example is here.
after putting validation rules, on jQuery's ready, just add $('.form-horizontal').valid(); to validate form.
See Fiddle, updated accordingly

jQuery Calculator - validation executes instead of calculator

I made a jQuery calculator that takes Fuel amount and Burn rate to give Time til empty to display on my screen. I also am using form validation.
When I click on the calculator button it runs form validation for some and tries to run the server-side code which is fine if I was clicking on the form submit button (and that button performs the way it should). But I have my calculator button "id" attribute and "name" attribute different than the form submit button. So I don't understand why when I click on the calculator button it tries to run form validation. In addition, it doesn't give me the total in the
$('#time-empty-field').val(time_empty);
field. Ideally, I want the calculator to show the total in the $('time-empty-field') and not run form validation.
I know my HTML is fine and from what I can see I don't see anything wrong with my jQuery. Maybe a different set of eyes can help on this. Any help would be much appreciated. Thanks!
$(function() {
$('#id').focus();
// To clear phone example when active
$('#phone').focus(function() {
var field = $(this);
if (field.val() == field.prop('defaultValue')) {
field.val('').css('color', 'black');
}
});
// Reveals System Report
$('#system-box input').click(function() {
if ($(this).attr('checked')) {
$('#system-report').slideDown('fast');
} else {
$('#system-report').slideUp('fast');
}
});
//Calculator
$('#calculator-submit-btn').submit(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
// Form validation plug-In
$('#form1').validate({
rules: {
id: {
required: true,
number: true
},
password: {
required: true
},
phone: {
required: true,
phoneUS: true
}
},
messages: {
id: {
required: "Please enter ID number."
},
password: {
required: "Please enter password."
},
phone: {
phoneUS: "Please enter a valid phone number."
}
}
});
});
$('#calculator-submit-btn').click(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
submit() can be used on submit forms only.
for more details chec jQuery API : http://api.jquery.com/submit/
Simply you cannot attach submit() event to a button , only to a form.

Categories