Validating React-Bootstrap-Typeahead input - javascript

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.

Related

Js: Function to detect field on signup form and fill it

I'm programming a chrome extension and I need to autofill form an the current visited site. I find the code of the Bitwarden autofill scrut but I'm novice so I don't know how to implement it to my code. Also, the variables that have to complete the fields are in the script.js, and idk were the autofill should be.
Try adding this to your script.js:
function getPasswordInput() {
return document.querySelector('form input[type="password"]')
}
function getFormElement() {
var passwordInput = getPasswordInput()
while (!(passwordInput instanceof HTMLFormElement)) {
passwordInput = passwordInput.parentElement
}
return passwordInput
}
function getUsernameInput() {
return getFormElement().querySelector('input[type="text"]')
}
if (getPasswordInput()) {
getUsernameInput().value = 'YOUR_USERNAME'
getPasswordInput().value = 'YOUR_PASSWORD'
}
This code checks if there are any input elements on the site which have the type password. If so it will autofill the form. You just need to replace YOUR_USERNAME and YOUR_PASSWORD with the username and password.

Incompatibility between validatorjs module and html5 validator?

I got an annoying problem in validating input fields using validatorjs module.
For the sake of clarity there's the input form image:
https://i.stack.imgur.com/OcRng.png
I'm trying to validate every rule with validatorjs, there's the code (I'm using React).
First function: checkValidity --->
checkValidity() {
let data = {
From: this.state.start,
To: this.state.end,
Category: this.state.category,
Age: this.state.age,
ExtraDrivers: this.state.extraDrivers,
EstimatedKm: this.state.estimatedKm
};
Validator.register('after', function (date, params, attribute){
const momentEnd = moment(date);
return moment(params).isBefore(momentEnd, 'day');
});
let rules = {
From: ['required', 'regex:/([12]\\d{3}/(0[1-9]|1[0-2])/(0[1-9]|[12]\\d|3[01]))/'],
To: ['required', 'regex:/([12]\\d{3}/(0[1-9]|1[0-2])/(0[1-9]|[12]\\d|3[01]))/', `after:${this.state.start}`],
Category: 'required',
Age: 'required|between:18,88',
ExtraDrivers: 'required|between:0,10',
EstimatedKm: 'required'
};
let validation = new Validator(data, rules, {
required: ':attribute is mandatory',
regex: ":attribute is not valid date format",
after: "To should be after From",
between: ":attribute should be between :min and :max"
});
return validation;
}
second function: submitHandler ---->
submitHandler = (event) => {
event.preventDefault();
console.log("SUBMITHANDLER");
let validation = this.checkValidity();
if (validation.passes()) {
console.log("YOOOOOOOOOOO");
}
else {
console.log("From has errors?: "+validation.errors.has('From'));
console.log("To has errors?: "+validation.errors.has('To'));
console.log("Category has errors?: "+validation.errors.has('Category'));
console.log("Age has errors?: "+validation.errors.has('Age'));
this.setState({
reportMessage: validation.errors.first('From') ||
validation.errors.first('To') ||
validation.errors.first('Category') ||
validation.errors.first('Age') ||
validation.errors.first('ExtraDrivers')
});
}
}
Well, the problem is that validatorjs can catch validation errors for the first three Form.Control (in "validation.errors" array). This happen (I think, not sure at all) because when I force a validation error (for example) on the Age Form.Control it's been catched by HTML5 validator (don't know why) thanks to the "invalid" event. I noticed that if it happens the submit event will not be triggered, so the submitHandler callback function will not be called and my customized validation error message won't be displayed.
Images of what happens in browser:
https://i.stack.imgur.com/u2ffd.png ["From" custom error message]
https://i.stack.imgur.com/A2bQp.png ["To" custom error message]
https://i.stack.imgur.com/AIvIF.png ["Category" custom error message]
https://i.stack.imgur.com/1p6ll.png ["Age" NOT custom error message (problem here)]
https://i.stack.imgur.com/0ebm6.png [logs from submitHandler callback]
I need the same behaviour of the first three input fields for the rest of them.
Thank you for your help!
P.S: here a stackblitz link to try it on your own
https://stackblitz.com/edit/react-zaho8x?file=index.js
P.S(2.0): [SOLVED] If you check the Age Form.Control component on line 122 (on stackblitz) you can see that there are min and max html validation keys. Removing them I solved. The same happens for extraDrivers input field.
<Form.Control name="age" type="number" value={this.state.age} min={18} max={88} placeholder={18} onChange={(ev) => this.changeHandler(ev.target.name, ev.target.value)}/>

Two text fields, only one required to be filled (either)

So I have two fields in my webpage, one for telephone number and the other for email address, I need to make either one of them required to be filled by using JavaScript NOT jQuery. Most of the answers I found here are for jQuery, any solutions with JavaScript would be much appreciated. Thanks!
function User_one(){
var phone = document.getElementById('PhoneText2').value;
var mail = document.getElementById('EmailText1').value;
if (phone && mail == ""){
alert("An error occurred.");
}else{
return false;
}
}
Update with actual code
Here's how I'd do it
(function () {
document.getElementById('myForm').addEventListener('submit', function(event){
// Get the length of the values of each input
var phone = document.getElementById('PhoneText2').value.length,
email = document.getElementById('EmailText1').value.length;
// If both fields are empty stop the form from submitting
if( phone === 0 && email === 0 ) {
event.preventDefault();
}
}, false);
})();
Since you haven't supplied any code for us to work with, I'll answer in pseudo-code:
On form submission {
If (both telephone and email is empty) {
throw validation error
}
otherwise {
submit the form
}
}
If you show me your code I'll show you mine :-)

Remove literals from input value before validation and submit

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.

Focus on first invalid text field after form validation

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Categories